Powershell error handling: do something if NO error occured

泪湿孤枕 提交于 2019-12-21 11:35:51

问题


I've been searching around for this but can't seem to find it. I'm having a script with a try {} catch {} statement. I'd like to add an action if NO error occured.

Eg

try { something }
catch { "Error occured" }
if (!error) {
"No Error Occured"
}

How can I test if no error occured in the statement?

Thanks in advance

Walter


回答1:


Chek the automatic-variable $error after cleared

$error.clear()
try { something }
catch { "Error occured" }
if (!$error) {
"No Error Occured"
}



回答2:


Another way:

$ErrorOccured = $false

try 
{ 
   $ErrorActionPreference = 'Stop'
   ...something...
}
catch
{
   "Error occured"
   $ErrorOccured=$true
}

if(!$ErrorOccured) {"No Error Occured"}

.




回答3:


What about,

something
If ($?)
{
    "No error"
}
Else
{
    "Error"
}

This will work for non terminating errors too.



来源:https://stackoverflow.com/questions/10496885/powershell-error-handling-do-something-if-no-error-occured

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!