Powershell错误等价于try-catch吗?

问题描述:

我正在编写的脚本经常尝试删除它没有能力的文件。这会引发一些错误,一个是没有足够访问权限的错误,另一个是稍后尝试删除包含第一个问题的非空文件夹的错误。这些东西很好,但我仍然想输出错误消息,如果有任何东西被抛出,那不是这两条消息之一。Powershell错误等价于try-catch吗?

try-catch块没有捕捉任何东西,因为它们是错误而不是异常。

try 
{ 
    Remove-Item D:\backup\* -Recurse 
    Write-Host "Success" -ForegroundColor Green 
    Write-Host $error.count 
} 
catch 
{ 
    Write-Host "caught!" -ForegroundColor Cyan 
} 

即使$error.count里面有错误,它仍然成功地完成了try-block。我是不是每次都要手动检查$ error是否有新内容,还是有更好的方法来做这件事?谢谢!

在Try/Catch中,仅在终止错误时调用Catch块。

使用ErrorAction通用参数来强制所有的错误被终止:

try 
{ 
    Remove-Item D:\backup\* -Recurse -ErrorAction Stop 
    Write-Host "Success" -ForegroundColor Green 
    Write-Host $error.count 
} 
catch 
{ 
    Write-Host "caught!" -ForegroundColor Cyan 
} 

或者使用全局erroraction:

try { 
$erroractionpreference = 'stop' 
Remove-Item D:\backup\* -Recurse 
Write-Host "Success" -ForegroundColor Green 
Write-Host $error.count 
} catch { 
Write-Host "caught!" -ForegroundColor Cyan 
}