如何捕获命令抛出的错误消息? [英] How to capture error messages thrown by a command?

查看:31
本文介绍了如何捕获命令抛出的错误消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个 PowerShell 脚本,我需要在其中捕获它抛出的错误消息.注意:根据PowerShell,没有错误,命令执行成功.

I am writing a PowerShell script where in I need to capture the error message that it's throwing. Note: according to PowerShell, there is no error and command is executed successfully.

例如:我试图从 SVN Link 下载一个包.链接实际上不存在.该脚本在控制台上向我显示错误消息.但是,当我尝试检查 $_$?$error 时,我没有看到任何错误消息.但是,$LASTEXITCODE 返回值 1.我需要获取确切的错误消息.

For example: I tried to download a package from SVN Link. The Link actually is not present. The script is showing me error message on the console. However, when I tried to check $_ or $? or $error, I did not see any error message. However, $LASTEXITCODE returned value 1. I need to get the exact error message.

推荐答案

如果出现错误信息,需要捕获错误流:

If you get an error message, you need to capture the error stream:

$msg = command 2>&1

command 2>error.txt

PowerShell 将其消息写入不同的流,这些流可以重定向到文件以捕获相应的输出.

PowerShell writes its messages to different streams that can be redirected to files for capturing the respective output.

  • 流 1(默认):常规输出(STDOUT")
  • 流 2:错误消息(STDERR"),包括来自外部程序的错误消息
  • 流 3:警告消息
  • 流 4:详细消息
  • 流 5:调试消息
  • 流 6:信息消息(仅限 PowerShell v5 和更新版本)

要捕获文件中的特定流,您需要将流编号重定向到文件名.例如

To capture a particular stream in a file you need to redirect the stream number to a file name. For instance

command 2>"C:\path\to\error.log"

将在文件 C:\path\to\error.log 中捕获由 command 产生的所有错误消息.如果您想附加到文件而不是在每次运行时覆盖它,请使用 2>> 而不是 2>.

would capture all error messages produced by command in the file C:\path\to\error.log. Use 2>> instead of 2> if you want to append to the file instead of overwriting it with each run.

您还可以将其他流与 STDOUT 结合以处理/重定向所有命令输出:

You can also combine other streams with STDOUT to process/redirect all command output:

command >>"C:\path\to\all.log" *>&1

请参阅获取有关_重定向的帮助这个脚本专家文章,了解有关流和重定向的更多信息.

See Get-Help about_Redirection or this Scripting Guy article for more information about streams and redirection.

注意事项:

  • *> 重定向是在 PowerShell v3 中引入的,因此它在 PowerShell v2 及更早版本中不起作用.
  • PowerShell v5 引入了一个新流(信息,流编号 6),因为人们一直在滥用 Write-Host,因为他们不了解 cmdlet 的用途.
  • The *> redirection was introduced with PowerShell v3, hence it won't work in PowerShell v2 and earlier.
  • PowerShell v5 introduced a new stream (Information, stream number 6) since people kept misusing Write-Host because they didn't understand what the cmdlet was intended for.

这篇关于如何捕获命令抛出的错误消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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