Reputation: 2301
How to rewrite below code so it can be grouped into only one IF statements instead of multiple IF and only execute remove command if all files (outPath,outPath2, outPath3) are exists.
If ($outPath){
Remove-Item $outPath
}
If ($outPath2){
Remove-Item $outPath2
}
If ($outPath3){
Remove-Item $outPath3
}
Upvotes: 0
Views: 156
Reputation: 46690
If you want to be sure all the paths exist you can use Test-Path
with -notcontains
to get the results you want.
$paths = $outPath1, $outPath2, $outPath3
if ((test-path $paths) -notcontains $false){
Remove-Item -Path $paths
}
Test-Path
works with arrays of paths. It will return an array booleans. If one of the paths didn't exist then a false would be returned. The if is conditional based on that logic.
Since you will only remove them if they exist you don't need to worry about their existence with the Remove-Item
cmdlet.
Upvotes: 2
Reputation: 2904
this will remove the files if they exist and supress errors if the files are not found. The downside is that if there should be errors other than (path not found) then those would be supressed as well.
Remove-Item -Path $outPath,$outPath1,$outPath2 -ErrorAction SilentlyContinue
EDIT
if you only want to remove if all 3 files exist then:
if( (Test-Path $outPath) -and (Test-Path $outPath1) -and (Test-Path $outPath2) )
{
try
{
Remove-Item -Path $outPath,$outPath1,$outPath2 -ErrorAction Stop
}
Catch
{
throw $_
}
}
Upvotes: 1