繁体   English   中英

抑制 cmd 命令上的错误 output Where-Object

[英]Suppress Error output Where-Object on a cmd command

我试图从 cmd 命令(gpresult / r)的 Where-Object 中抑制错误 output,首先我保存了 output 的变量,并添加了 gpresult Where-Object 的两个过滤器和过滤器变量, , 以查找用户应属于的两个 AD 组。

当用户不在任何这些组中时问题就出现了(这可能会发生,因为不是每个人都使用与这些组相关的程序),控制台会打印一个我们不希望用户看到的丑陋错误......我尝试将 -ErrorAction SilentlyContinue 添加到 Where-Object 无济于事,错误仍在弹出。

你们对此有任何线索吗? 这是代码,因此您可以更好地理解我要抑制的内容:

$gpresult = gpresult /r
$userGroups = ($gpresult | Where-Object -FilterScript {($_ -match 'Group1_*') -or ($_ -match 'Group2_*')} -ErrorAction SilentlyContinue).Trim()

提前致谢!

我不完全确定我理解您要做什么,但您可以将标准输出和标准错误流分开例如将 stderr 重定向到 null 将完全删除它。 如果将其添加到命令的末尾。

2>$null

2 是错误 stream

如果您想稍后将它们分开,您应该可以。 因为来自 stdout 的数据将是来自 stderr System.Management.Automation.ErrorRecord 对象的字符串和数据。

$gpresult = gpresult /r
$stderr = $gpresult | ?{ $_ -is [System.Management.Automation.ErrorRecord] }
$stdout = $gpresult | ?{ $_ -isnot [System.Management.Automation.ErrorRecord] }

我尝试将-ErrorAction SilentlyContinue添加到Where-Object无济于事,错误仍在弹出。

不需要的错误显示发生得更早,即在$gpresult = gpresult /r

That is, assigning a call to an external program such as gpresult to a PowerShell variable ( $gpresult =... ) captures that program's stdout output in the variable, while passing its stderr output through to the host (console).

因此,要通过简单地丢弃stderr output 来防止打印,请使用重定向2>$null

$gpresult = gpresult /r 2>$null

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM