在PowerShell脚本中处理命令提示符错误 [英] Handle command prompt error within PowerShell script

查看:108
本文介绍了在PowerShell脚本中处理命令提示符错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在PowerShell脚本中运行一些命令提示符命令,例如 schtasks 。我想知道如何处理PowerShell中命令所引发的错误。

I am trying to run a few command prompt commands like schtasks within a PowerShell script. I would like to know how to handle errors thrown by the command in PowerShell.

我尝试过:


  • & cmd.exe / c’schtasks / Query / TN xx || echo ERROR’

  • & cmd.exe / c‘ping.exe 122.1.1.1&&出口0 ||出口1'

  • Invoke-Expression -Command:$ command

  • & cmd.exe /c 'schtasks /Query /TN xx || echo ERROR'
  • & cmd.exe /c 'ping.exe 122.1.1.1 && exit 0 || exit 1'
  • Invoke-Expression -Command:$command

我无法运行这些命令,也无法在 try..catch 块中忽略或捕获异常PowerShell脚本。我知道有库,但仅限于PowerShell v2.0。

I'm unable to run these commands and ignore or catch exception in a try..catch block of the PowerShell script. I know there are libraries but I'm limited to PowerShell v2.0.

推荐答案

外部命令通常设置非零退出代码因错误而终止,因此您可以检查自动变量 $ LASTEXITCODE 具有非零值:

External commands usually set a non-zero exit code if they're terminating with an error, so you could check if the automatic variable $LASTEXITCODE has a non-zero value:

& cmd /c 'schtasks /Query /TN xx'
if ($LASTEXITCODE -ne 0) {
  'an error occurred'
}

但是请注意,有些程序使用非零退出代码获取非错误信息(例如 robocopy (使用退出代码低于8的状态信息),或 choice (使用退出代码表示所选的选项)。

Note, however, that there are some programs that use non-zero exit codes for non-error information, (e.g. robocopy, which uses the exit codes below 8 for status information, or choice, which uses the exit code to indicate the chosen option).

可以通过在CMD中重定向错误输出流来抑制外部命令的错误消息:

Error messages of the external command can be suppressed by redirecting the error output stream, either in CMD:

& cmd /c 'schtasks /Query /TN xx 2>nul'

或在PowerShell中:

or in PowerShell:

& cmd /c 'schtasks /Query /TN xx' 2> $null

这篇关于在PowerShell脚本中处理命令提示符错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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