Powershell script to check if a file exists
$strFileName="c:\filename.txt" If (Test-Path $strFileName){ # // File exists }Else{ # // File does not exist }
See Also:
Powershell: Delete File if Exists
Powershell: Delete Folder if Exists
Test-Path
Remove-Item
Thanks Man !
Works great, thanks!
Thank you!
Hey, thanks you this example saved the day for me! I would like to let everyone know that when using test-path in a if statement with a -Or you will need to put ( ) around each test-path for example:
$x = C:/test1.txt
$y = C:/test2.txt
if ((test-path $I) -or (test-path $y))
{
write-host “hello world!”
}
else
{
}
Superb… Got my answer in few secs
under PS 5, I found I had to put () around the variable as well:
if (Test-Path -LiteralPath ($pricelist)) {
$message.attachments.add($pricelist)
$msg = $pricelist+’ attached to email’
Write-Host $msg
}
else {
$msg = $pricelist+’ not found’
Write-Host $msg
}
Nice!
Wrapped around () when checking if file does not exist:
if (-not (Test-Path $path)) {
…
…
}
Thanks, this worked for me!
Just a few lines of code makes life easier.