简体   繁体   中英

Suppress Error output Where-Object on a cmd command

I'm trying to suppress an error output from a Where-Object of a cmd command (gpresult /r), first I saved the output of the gpresult to a variable, then I filtered the variable with the Where-Object and added two filters, to find two AD groups that the user should be member of.

The problem comes when the user is not in any of those groups (that it could happen because not everyone uses the programs related to those groups), the console prints a ugly error that we don't want the user to see... I tried adding -ErrorAction SilentlyContinue to the Where-Object with no avail, the error is still popping up.

Do you guys have any clue on this? Here's the code, so you can understand better what I'm trying to suppress:

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

Thanks in advance!

I am not completely sure I understand what you are trying to do but you can separate standard out and standard error streams For example redirecting stderr to null will completely remove it. If you add this to the end of your command.

2>$null

2 is error stream

If you want to separate them later you should be able to. Because data from stdout will be strings and data from stderr System.Management.Automation.ErrorRecord objects.

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

I tried adding -ErrorAction SilentlyContinue to the Where-Object to no avail, the error is still popping up.

The unwanted error display happens earlier , namely in $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).

Therefore, to prevent stderr output from printing by simply discarding it, use redirection 2>$null :

$gpresult = gpresult /r 2>$null

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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