在PowerShell脚本中处理命令提示符错误

编程入门 行业动态 更新时间:2024-10-25 16:24:33
本文介绍了在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脚本中处理命令提示符错误

本文发布于:2023-11-06 17:23:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1564317.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:脚本   命令提示符   错误   PowerShell

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!