【发布时间】:2019-09-26 14:13:03
【问题描述】:
在持续集成管道 (Azure DevOps) 中使用的部署后脚本中,我正在删除旧文件。
基本上,它是一个 PowerShell 脚本,可删除除部署目录中的当前文件夹之外的所有发布文件夹。
有时,Remove-Item 会因某种原因失败(例如,旧文件仍由部署机器上的某个人打开)
这没什么大不了的。我不想要一个错误说我的整个部署因此而失败。但是,我想要一个警告,所以我知道它发生了。
例如(MCVE):
Remove-Item INEXISTENT_FILE
问题:会导致错误。
尝试 1:
Remove-Item INEXISTENT_FILE -ErrorAction SilentlyContinue
问题:它完全消除了错误,这不是我想要的(我想要一个警告)
尝试 2:我尝试按照此处的建议使用 ErrorVariable:https://devblogs.microsoft.com/powershell/erroraction-and-errorvariable/
Remove-Item INEXISTENT_FILE -ErrorAction SilentlyContinue -ErrorVariable $removeItemError
if ($removeItemError) {
Write-Warning "Warning, something failed!"
}
问题:它不起作用,它不显示if 部分。如果我删除“SilentlyContinue”错误操作,它只会发出错误,并且在任何情况下都不会进入 if 部分。
尝试 3:我也尝试使用此处建议的 Try Catch 块:PowerShell -ErrorAction SilentlyContinue Does not work with Get-ADUser
Try {
Remove-Item INEXISTENT_FILE
}
Catch {
Write-Warning "Warning, something failed!"
}
问题:它也永远不会进入 catch 块(!?)
如果 Remove-Item 失败,任何人都有另一个选项来显示警告而不是错误?
【问题讨论】:
标签: powershell error-handling azure-devops