Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

powershell - Is there a way to set a variable up to place output to stdout or null?

I would like to set up a variable in my code that would ultimately define if I'll see some output or not.

  • "hello" writes to stdout
  • "hello" > $null supresses output

My idea is something like this:

$debugOutputSwitch = $true
$outputVar = $null
if ($debugOutputSwitch){ $outputVar = **STDOUT** }
...
Write-Host "Something I want out anyway"
"Something I might not want on STDOUT" > $outputVar

If this general idea is a way to go, then STDOUT is what I'm looking for

If this idea is completely wrong...well...then I'm lost

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What you want to read up on are output streams and redirection in Powershell. This includes information on all of the different output streams and how to control their relevance using built-in constructs. Just like there are the Write-Host and Write-Output cmdlets, there are also several others that control which stream to write to.

About the Output Streams

There are 6 streams in total. Make note of their numbers, because these stream identifiers are used to control which streams to redirect:

  • 1 - Success Stream - This stream is used when passing information along the Powershell Pipeline. This is the "default" stream, but can also be written to with Write-Output.
  • 2 - Error Stream - Errors should be written to this stream. Can be written to with Write-Error, accompanied by further error information.
  • 3 - Warning Stream - Used to write warning information. Can be written to with Write-Warning.
  • 4 - Verbose Stream - Used to write verbose output. Does not display by default but can be made to display by either setting $VerbosePreference = "Continue", or by using the [CmdletBinding()] attribute on a function or script and passing in the -Verbose flag. Write to the verbose stream with Write-Verbose.
  • 5 - Debug Stream - Used to write to the debug stream, and optionally trigger a breakpoint. Does not display or trigger a breakpoint by default, but can be controlled with the $DebugPreference variable, or by using the [CmdletBinding()] attribute on a script or function and using the -Debug flag. You can write to the debug stream by using the Write-Debug cmdlet.
  • 6 - Information Stream - Can be written to by Write-Host. This is the console host output and is not part of the pipeline.

Redirecting Streams

You can use redirection operators to redirect other streams to the success stream as well. Each stream above has a number associated with it. This is the numeric representation of each stream.

The redirection operators are as follows:

  • > - Redirect success stream to file (overwrite)
  • #> - Redirect the # stream to file (e.g. 2> somefile.txt)
  • >> - Redirect success stream to file (appends, you can also use a numbered stream as with the overwrite file operator)
  • >&1 - Redirect any stream to success stream (note that unlike the other redirection operators you can only redirect to the success stream. Using other stream identifiers will result in an error).

Also note that in place of a stream number, you can use * which will redirect all streams at the same time.

Here are some examples of redirecting output from one stream to another (if you're familiar with it, it's somewhat UNIX-y):

# Write success stream to file
Write-Output "Here is some text for a file" > .somefile.txt

# Write error stream to file (you have to first
Write-Error "Some error occurred" 2> .somefile.txt

# Redirect all error output to the success stream
$myErrorOutput = Write-Error "My error output" 2>&1

# Append all script output streams to a single file
Get-OutputFromAllStreams.ps1 *>> somefile.txt

Output to a File and the Pipeline Simultaneously

You can redirect the output stream to a file and the pipeline at the same time as well, using the Tee-Object cmdlet:

$myString = "My Output" | Tee-Object -FilePath .somefile.txt

Sample function to show how to use the different Write- cmdlets

Note how the following function is decorated with the [CmdletBinding()] attribute. This is key in making the -Verbose and -Debug switches work without you having to define them yourself.

function Write-DifferentOutputs {
  [CmdletBinding()]
  # These all visible by default but only the output stream is passed down the pipeline
  Write-Output "Output stream"
  Write-Warning "Warning stream"
  Write-Error "Error stream"
  Write-Host "Information stream"

  # These are not visible by default, but are written when the `-Verbose` or `-Debug` flags are passed
  # You can also manually set the $VerbosePreference or $DebugPreference variables to control this without parameters
  Write-Verbose "Verbose stream"
  Write-Debug "Debug stream"
}

Call the above function with the -Verbose or -Debug switches to see how the behavior differs, and also call it with neither flag.

Redirecting output to $null if you really need to

If there is output that you never want to see or for some other reason using the Write- cmdlets to write to the Verbose or Debug streams isn't an option, you can still redirect output to $null or make use of the Out-Null cmdlet. Recall the numbered streams at the top of this answer, they will be referenced here:

Using redirection

# Don't forget that *> redirects ALL streams, and may be what you want
Write-Output 'Success Stream' > $null
Write-Error 'Error Stream' 2> $null
Write-Warning 'Warning Stream' 3> $null
Write-Verbose 'Verbose Stream' 4> $null
Write-Debug 'Debug Stream' 5> $null
Write-Host 'Information Stream (yes you can suppress/redirect me)' 6> $null

Using Out-Null

Remember, you can redirect other streams to the success stream by redirecting the output to &1.

# Remember, to pass information on the pipeline
# it MUST be on the success stream first

# Don't forget that *> redirects ALL streams, and may be what you want
Write-Output 'Success Stream' | Out-Null
Write-Error 'Error Stream' 2>&1 | Out-Null
Write-Warning 'Warning Stream' 3>&1 | Out-Null
Write-Verbose 'Verbose Stream' 4>&1 | Out-Null
Write-Debug 'Debug Stream' 5>&1 | Out-Null
Write-Host 'Information Stream (yes you can suppress/redirect me)' 6>&1 | Out-Null

Redirecting whole command outputs to Write- cmdlets

You can easily pipe all output of a command or cmdlet to one of the Write- cmdlets. I'll use the Write-DifferentOutputs provided earlier in my example below, but this will work with any cmdlet, script, or command you run:

Write-DifferentOutputs *>&1 | Write-Verbose

What the above will do is only show the command output if $VerbosePreference = $Continue, or if you passed -Verbose as an argument to your script or function.

In Summarium

In your original question, you are attempting to reinvent a wheel that Powershell already supports fairly well. I would suggest that you learn how to make use of the different Write-Output cmdlets for each stream and especially learn how to make use of the Write-Warning, Write-Verbose, Write-Error, and Write-Debug cmdlets.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...