Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.)

like image 890
ted Avatar asked May 04 '11 09:05

ted


People also ask

How do I redirect output in PowerShell?

There are two PowerShell operators you can use to redirect output: > and >> . The > operator is equivalent to Out-File while >> is equivalent to Out-File -Append . The redirection operators have other uses like redirecting error or verbose output streams.

How do I capture a verbose output in PowerShell?

For example to capture only verbose output you can run the command as a subexpression. When run this outputs the error and warning objects to console but the verbose objects are saved into $VerboseOnly and the output objects are saved into $OutputOnly.

What does $null mean in PowerShell?

$null is an automatic variable in PowerShell used to represent NULL. You can assign it to variables, use it in comparisons and use it as a place holder for NULL in a collection. PowerShell treats $null as an object with a value of NULL. This is different than what you may expect if you come from another language.


2 Answers

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 
like image 124
J Bills Avatar answered Oct 09 '22 12:10

J Bills


This should work.

 $foo = someFunction 2>$null 
like image 32
ravikanth Avatar answered Oct 09 '22 12:10

ravikanth