Redirecting output to $ null in PowerShell, but ensuring that the variable is saved

I have a code:

$foo = someFunction 

This displays a warning message that I want to redirect to $ null:

 $foo = someFunction > $null 

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

How to redirect a warning to $ null, but keep $ foo anyway?

Also, how do you redirect both standard output and standard error to null? (On Linux, this is 2>&1 )

+47
powershell
May 4 '11 at 9:16
source share
5 answers

I would prefer this method to redirect standard output (native PowerShell) ...

 ($foo = someFunction) | out-null 

But this also works:

 ($foo = someFunction) > $null 

To redirect only the standard error after defining $ foo with the result "someFunction", do

 ($foo = someFunction) 2> $null 

This is actually the same as above.

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

 $foo = (someFunction 2> $null) 

To redirect both options, you have several options:

 2>&1>$null 2>&1 | out-null 
+95
Jun 23 2018-11-11T00:
source share
— -

That should work.

  $foo = someFunction 2>$null 
+10
May 4 '11 at 9:49 a.m.
source share

If these are the errors you want to hide, you can do it like this:

 $ErrorActionPreference = "SilentlyContinue"; #This will hide errors $someObject.SomeFunction(); $ErrorActionPreference = "Continue"; #Turning errors back on 
+3
09 Oct '13 at 14:15
source share

Warning messages must be recorded using the Write-Warning cmdlet, which allows warning messages with the -WarningAction parameter or the $WarningPreference automatic variable. The function must use CmdletBinding to implement this function.

 function WarningTest { [CmdletBinding()] param($n) Write-Warning "This is a warning message for: $n." "Parameter n = $n" } $a = WarningTest 'test one' -WarningAction SilentlyContinue # To turn off warnings for multiple commads, # use the WarningPreference variable $WarningPreference = 'SilentlyContinue' $b = WarningTest 'test two' $c = WarningTest 'test three' # Turn messages back on. $WarningPreference = 'Continue' $c = WarningTest 'test four' 

To make this shorter on the command line, you can use -wa 0 :

 PS> WarningTest 'parameter alias test' -wa 0 

Write-Error, Write-Verbose and Write-Debug offer similar functionality for the respective message types.

+2
Feb 15 '12 at 14:20
source share

Assuming the error message is returned first:

  $foo = someFunction $foo = $foo[1] 

If the variable value is returned first:

  $foo = someFunction $foo = $foo[0] 
-2
May 05 '11 at 3:43
source share



All Articles