Home > front end >  Powershell - Supress Error output Where-Object on a cmd command
Powershell - Supress Error output Where-Object on a cmd command

Time:09-23

I'm trying to supress 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 dont want the user to see... I tried adding -ErrorAction SilentlyContinue to the Where-Object with no avail, the error is still poping up.

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

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

Thanks in advance!

CodePudding user response:

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] }

CodePudding user response:

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
  • Related