Powershell – Redirecting output to $null in PowerShell, but ensuring the variable remains set

powershell

I have some code:

$foo = someFunction

This outputs a warning message which I want to redirect to $null:

$foo = someFunction > $null

The problem is that when I do this, while successfully supressing the warning message, it also has the negative side-effect of NOT populating $foo with the result of the function.

How do I redirect the warning to $null, but still keep $foo populated?

Also, how do you redirect both standard output and standard error to null? (In Linux, it's 2>&1.)

Best Answer

I'd prefer this way to redirect standard output (native PowerShell)...

($foo = someFunction) | out-null

But this works too:

($foo = someFunction) > $null

To redirect just standard error after defining $foo with result of "someFunction", do

($foo = someFunction) 2> $null

This is effectively the same as mentioned above.

Or to redirect any standard error messages from "someFunction" and then defining $foo with the result:

$foo = (someFunction 2> $null)

To redirect both you have a few options:

2>&1>$null
2>&1 | out-null