如何仅在 PowerShell 中的变量中捕获错误输出 [英] How to capture error output only in a variable in PowerShell

查看:23
本文介绍了如何仅在 PowerShell 中的变量中捕获错误输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将 PowerShell 命令的 stderr 输出存储在一个变量中.我不想将它存储在文件中,也不想包含标准输出,只包含错误输出.

I want to store the stderr output of a PowerShell command in a variable. I don't want to store it in a file and I don't want standard output included, just the error output.

这会重定向到一个名为 error.txt 的文件:

This redirects to a file named error.txt:

&$command $params 2> error.txt

& $command $params 2> error.txt

这将 stderr 和 stdout 都重定向到 $output 变量:

This redirects both stderr and stdout to the $output variable:

$output = &$command $params 2>&1

$output = & $command $params 2>&1

但我想将错误输出存储在一个变量中(与上面的error.txt文件的内容相同),而不向文件写入任何内容.我该怎么做?

But I want to store only the error output in a variable (the same as the content of the error.txt file above), without writing anything to file. How do I do that?

推荐答案

您可以以稍微不同的方式调用命令,并在 PowerShell 中使用 -ErrorVariable 参数:

You can call the command a slightly different way and use the -ErrorVariable parameter in PowerShell:

Invoke-Expression "$command $params" -ErrorVariable badoutput

$badoutput 现在将包含错误字符串的内容.

$badoutput will now contain the contents of the error string.

这篇关于如何仅在 PowerShell 中的变量中捕获错误输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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