簡體   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