简体   繁体   English

检测PowerShell脚本执行错误

[英]Detecting PowerShell script is executed with error

I have a PowerShell script: 我有一个PowerShell脚本:

...
Any-Command -ErrorCode Stop
...

Then I call this script from a bat script: 然后我从蝙蝠脚本中调用此脚本:

...
powershell myscript.ps1
...

Now I would like to know in the bat script if the called PowerShell script is stopped on error and not reached the end of the script. 现在,我想在bat脚本中知道调用的PowerShell脚本是否因错误而停止并且未到达脚本的末尾。 How to do it? 怎么做?

One way to do it would be to add a top level trap statement to your script, something like: 一种方法是在脚本中添加一个顶级陷阱语句,例如:

trap {
   exit 1; # or whatever error code
}

Note: trap may be considered old fashioned (although I like it top-level), the other option would be a try-finally around your whole script. 注意:trap可能被认为是老式的(尽管我最喜欢它),另一个选择是围绕整个脚本进行尝试。

So when Any-Command exits with an exception, the trap statement is executed and the script exits with error code 1. If you don't add this, Powershell will exit with error code 0 (after all Powershell ran just fine, although the script didn't). 因此,当Any-Command异常退出时,将执行trap语句,并且脚本将以错误代码1退出。如果不添加此代码,Powershell将以错误代码0退出(毕竟,Powershell运行得很好,尽管该脚本没有)。

You can then detect the error code in a bat script using something like: 然后,您可以使用以下命令在bat脚本中检测错误代码:

powershell -noprofile -noninteractive -file <<your script>>

IF ERRORLEVEL 1 (echo ERROR) ELSE (echo OK)

pause

This will detect any error code of 1 or higher. 这将检测到1或更高的任何错误代码。

You can also use %ERRORLEVEL% but be wary that this may be overridden as an environment variable. 您也可以使用%ERRORLEVEL%但请注意,它可能会被环境变量覆盖。

Note: if you're running your script in a nested runspace, you could consider using $host.SetShouldExit(1) to ensure the root host exits as well. 注意:如果要在嵌套运行空间中运行脚本,则可以考虑使用$host.SetShouldExit(1)来确保根主机也退出。

Just adding to the answer given by Marcus 只需添加马库斯给出的答案

I noticed that the trap code even hides the actual error. 我注意到陷阱代码甚至隐藏了实际错误。 In my case I needed the actual error occurred. 就我而言,我需要发生实际错误。 Just adding the modified code for the completion. 只需添加修改后的代码即可完成。

 trap 
    { 
        write-error $("Error: " + $_.Exception.Message); 
        exit 1; # or whatever error code 
    } 

More info at http://huddledmasses.org/trap-exception-in-powershell/ 有关更多信息, 访问http://huddledmasses.org/trap-exception-in-powershell/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM