Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking a list to see if file exist in powershell?

I have a list of files that I want to check a directory in powershell 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 this possible?

like image 438
user3266638 Avatar asked Jan 24 '26 14:01

user3266638


1 Answers

You could use the 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"}

Edit: For the updated file names, here is how you could put them in an array to be looped through.

"testFile","Base","ErrorFile","UploadError" | ForEach-Object {
    Test-Path  "${filePath}${currentDate}$_.txt"
}
like image 190
BenH Avatar answered Jan 26 '26 22:01

BenH