Checking a list to see if a file exists in PowerShell?
I have a list of files that I want to check in the powershell directory to see if they exist. I'm not too familiar with powershell, but this is what I have so far that doesn't work.
$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)
}
Is it possible?
+3
source to share
2 answers
You can use the cmdlet Test-Path
.
$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"}
Edit: For updated filenames, here's how you could put them in an array that will loop.
"testFile","Base","ErrorFile","UploadError" | ForEach-Object {
Test-Path "${filePath}${currentDate}$_.txt"
}
+4
source to share