[英]Powershell remove files
如何重写下面的代码,以便可以将其分为一个IF语句而不是多个IF,并且仅在存在所有文件(outPath,outPath2,outPath3)的情况下才执行remove命令。
If ($outPath){
Remove-Item $outPath
}
If ($outPath2){
Remove-Item $outPath2
}
If ($outPath3){
Remove-Item $outPath3
}
如果要确保所有路径都存在,可以将Test-Path
与-notcontains
一起使用以获取所需的结果。
$paths = $outPath1, $outPath2, $outPath3
if ((test-path $paths) -notcontains $false){
Remove-Item -Path $paths
}
Test-Path
可用于路径数组。 它将返回一个布尔值数组。 如果其中一个路径不存在,则将返回false。 if是基于该逻辑的条件。
由于仅在它们存在的情况下才将它们删除,因此您无需担心它们是否存在,而使用Remove-Item
cmdlet。
如果文件存在,这将删除它们;如果找不到文件,则会抑制错误。 不利的一面是,如果除了(未找到路径)之外还有其他错误,那么这些错误也会被抑制。
Remove-Item -Path $outPath,$outPath1,$outPath2 -ErrorAction SilentlyContinue
编辑
如果您只想删除所有3个文件都存在,则:
if( (Test-Path $outPath) -and (Test-Path $outPath1) -and (Test-Path $outPath2) )
{
try
{
Remove-Item -Path $outPath,$outPath1,$outPath2 -ErrorAction Stop
}
Catch
{
throw $_
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.