简体   繁体   中英

Powershell remove files

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
}

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.

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 $_
        }

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM