如何从Remove-Item捕获错误并发出警告? [英] How to catch error from Remove-Item and emit a warning instead?

查看:197
本文介绍了如何从Remove-Item捕获错误并发出警告?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在用于持续集成管道(Azure DevOps)的部署后脚本中,我正在删除旧文件.

In a post-deployment script used in a continuous integration pipeline (Azure DevOps), I'm removing old files.

基本上,这是一个PowerShell脚本,可删除部署目录中的每个发行文件夹,但当前文件夹除外.

Basically, it's a PowerShell script that removes every release folder but the current one in the deployment directory.

有时,Remove-Item出于某种原因而失败(例如,旧文件仍由部署机器的某人打开)

Sometimes, the Remove-Item fails for some reason (old file still opened by someone one the deplyoment machine, for instance)

这没什么大不了的.我不想因为我的整个部署失败而出错.但是,我想要一个警告,所以我知道它发生了.

It's not a big deal. I don't want an error saying my whole deployment failed because of this. However, I want a warning, so I'm aware that it happened.

例如(MCVE):

Remove-Item INEXISTENT_FILE

问题:它会导致错误.

尝试1:

Remove-Item INEXISTENT_FILE -ErrorAction SilentlyContinue

问题:它完全消除了错误,这不是我想要的(我想要警告)

Problem : It removes the Error completely, that's not what I want (I want a warning)

尝试2:我尝试按照此处的建议使用ErrorVariable: https://devblogs.microsoft.com/powershell/erroraction-and-errorvariable/

Attempt 2 : I tried to use ErrorVariable as recommended here : 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部分.

Problem : it doesn't work, it doesn't show the if part. If I remove "SilentlyContinue" error action, it just emits an error, and in any case never goes into the if part.

尝试3:我也尝试使用这里建议的Try Catch块:

Attempt 3 : I tried to use also Try Catch block as proposed here : PowerShell -ErrorAction SilentlyContinue Does not work with Get-ADUser

Try {
    Remove-Item INEXISTENT_FILE
}
Catch {
    Write-Warning "Warning, something failed!"
}

问题:它也永远不会进入catch块(!?)

Problem : it never goes into the catch block either (!?)

如果Remove-Item失败,任何人都可以显示警告而不是错误?

Anyone has another option to show a warning instead of an error if Remove-Item fails ?

推荐答案

Remove-Item产生的错误被认为是非终止"的,这意味着它会被"try/catch"忽略.要使它变得可见"以尝试/捕获",请使用ErrorAction参数:

The error produced by Remove-Item is considered 'non-terminating', which means that it is ignored by 'try/catch'. To force it to become 'visible' to 'try/catch' use the ErrorAction parameter:

Remove-Item INEXISTENT_FILE -ErrorAction Stop

或者,您可以在脚本级别(例如,对所有后续命令)进行以下更改:

Alternatively, you can change this at the script level (i.e. for all subsequent commands) like this:

$ErrorActionPreference = 'Stop'

可以使用$_.Exception.Message$error[0]

这篇关于如何从Remove-Item捕获错误并发出警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆