Powershell检查文件是否存在

时间:2016-12-06 14:35:24

标签: powershell csv

在Windows 7 x64上,Powershell 3.0:

我有一个下载文件的目录,这是用.csv文件完成的。 这些文件的样本是:

008KS04.zip
008KS05.zip
008KS06.zip
008KS07.zip
008KS08.zip
008KS09.zip

我有一个Csv,这是一个样本:

Documentnummer,Versie,Status,Geocode,IDS datum,Documentgroep (Omsch),Documenttype (Wrd),Tekeningnummer
550164,I,AB,008,26.03.2016,Themalagen OI,KS,008KS09.zip
550163,D,AB,008,19.07.2013,Themalagen OI,KS,008KS08.zip
550162,D,AB,008,19.07.2013,Themalagen OI,KS,008KS07.zip
550161,C,AB,008,19.07.2013,Themalagen OI,KS,008KS06.zip
550160,D,AB,008,19.07.2013,Themalagen OI,KS,008KS05.zip
550159,E,AB,008,15.08.2014,Themalagen OI,KS,008KS04.zip

所以,让我们说文件在c:\ test \
中 和C:\ drawings.csv中的csv 我想要csv中缺少的文件,比方说C:\ missing.csv
起初我尝试使用变量中的一个绘图:

$drawnr = '008KS09.zip'
$destcsv = "C:\missing.csv"
Set-Location C:\test
    If(Test-Path -Path ${drawnr}) {
       Write-Output "${drawnr}'.zip' exists"

  } Else {

    Write-Output "${drawnr}'.zip' doesnt exist"
    ${drawnr} | Export-Csv $destcsv -Append -NoTypeInformation

}

The output when having an existing and a non existsing drawing in the variable
这很完美,看到图像,但使用CSV作为输入,我无法让它工作 这就是我到目前为止所做的:

$sourcecsv = 'C:\drawings.csv'
$destcsv = 'C:\missing.csv'
Set-Location 'C:\test\'

Import-Csv $sourcecsv | Select-object -Property Tekeningnummer | ForEach {

    Write-Output "${_} is the current object" #For Testing purpuse
If (Test-Path -Path ${_}) {

    Write-Output "${_} does exist"

  } Else {

    Write-Output "${_} doesnt exist"
    ${_} | Export-Csv $destcsv -Append -NoTypeInformation
    }
}

这告诉我没有文件存在,而所有文件都存在。
查看图片以查看PowerShell的输出以及写入missing.csv的内容 The picture of the output where all files are reported as non existend

3 个答案:

答案 0 :(得分:0)

我不确定我的意图,但看起来这可能有用。

$sourcecsv = 'C:\drawings.csv'
$destcsv = 'C:\missing.csv'
Set-Location 'C:\test\'

Import-Csv $sourcecsv | ForEach {

    Write-Output "${_} is the current object" #For Testing purpuse
    $TK = $_.Tekeningnummer
If (Test-Path -Path $TK) {

    Write-Output "$TK does exist"

  } Else {

    Write-Output "$TK doesnt exist"
    $_ | Export-Csv $destcsv -Append -NoTypeInformation
    }
}

答案 1 :(得分:0)

不确定${_}是否是我不知道的新语法,但我无法让它在我的PS4主机上工作,因此我将其更改为我的正常$_回答。除此之外,您只需要像@DaveSexton所建议的那样ExpandProperty

Import-Csv $sourcecsv | Select-object -ExpandProperty Tekeningnummer | ForEach {

Write-Output "$($_) is the current object" #For Testing purpuse
If (Test-Path -Path $($_) {

  Write-Output "$($_) does exist"

} Else {

  Write-Output "$($_) doesnt exist"
  $_ | Export-Csv $destcsv -Append -NoTypeInformation
}
}

答案 2 :(得分:0)

就这么做;)

$sourcecsv = 'C:\drawings.csv'
$destcsv = 'C:\missing.csv'
$dirtest='C:\test\'

Import-Csv $sourcecsv | where {-not (Test-Path "$dirtest$($_.Tekeningnummer)") } | export-csv $destcsv -NoTypeInformation