user3266638
user3266638

Reputation: 449

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?

Upvotes: 3

Views: 2827

Answers (2)

BenH
BenH

Reputation: 10044

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"
}

Upvotes: 4

G42
G42

Reputation: 10019

Yes, you can do this in PowerShell.

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

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

Upvotes: 0

Related Questions