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

查看:129
本文介绍了如何仅在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.

这将重定向到名为<$ c的文件$ c> 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天全站免登陆