检查列表以查看文件是否存在于 powershell 中?

Checking a list to see if file exist in powershell?

我有一个文件列表,我想检查 powershell 中的目录以查看它们是否存在。我对 powershell 不太熟悉,但这是我目前所拥有的,但这是行不通的。

$filePath = "C:\Desktop\test\"
$currentDate = Get-Date -format yyyyMMdd

$listOfFiles = 
"{0}{1}testFile.txt",
"{0}{1}Base.txt",
"{0}{1}ErrorFile.txt",
"{0}{1}UploadError.txt"`
-f $filePath, $currentDate

foreach ( $item in $listOfFiles ) 
{ 
    [System.IO.File]::Exists($item)
}

这可能吗?

是的,您可以在 PowerShell 中执行此操作。

$filePath = "C:\Desktop\test$((Get-Date).ToString("yyyyMMdd"))"

foreach ( $n in 1..4 ) {
    Test-Path $($filePath +"file$n.txt")
}

您可以使用 Test-Path cmdlet。

$filePath = "C:\Desktop\test\"
$currentDate = Get-Date -format yyyyMMdd
#I'm using 1..4 to create an array to loop over rather than manually creating each entry
#Also used String Interpolation rather than -f to inject the values
1..4 | ForEach-Object {Test-Path  "${filePath}${currentDate}file$_.txt"}

编辑: 对于更新的文件名,这里是如何将它们放入数组中以进行循环的方法。

"testFile","Base","ErrorFile","UploadError" | ForEach-Object {
    Test-Path  "${filePath}${currentDate}$_.txt"
}