Redirection

  command >  filename     # Redirect command output to a file (overwrite)

  command >> filename     # APPEND into a file

  command 2> filename     # Redirect Errors from operation to a file(overwrite)

  command 2>> filename    # APPEND errors to a file

  command 2>&1            # Add errors to results

  command 1>&2            # Add results to errors

  command | command       # This is the basic form of a PowerShell Pipeline

In PowerShell 3.0+

  command 3> warning.txt  # Write warning output to warning.txt 

  command 4>> verbose.txt # Append verbose.txt with the verbose output 

  command 5>&1            # Writes debug output to the output stream 

  command *> out.txt      # Redirect all streams (output, error, warning, verbose, and debug) to out.txt

In PowerShell you must redirect only the commands that will output string data:

if ($demo -eq $null) {Echo 'result'} >demo.txt #this will fail
if ($demo -eq $null) {Echo 'result' >demo.txt} #this will work

Redirecting output to Null (to discard the output from a cmdlet) can be done with out-null, but a far faster method is redirecting to the $null automatic variable:

PS C:\> get-childitem > $null

In PowerShell it is not possible to redirect the output of an entire session (so Powershell.exe .... >filename.txt won't work) however a very similar text output can be produced using the Start-Transcript cmdlet.

The text files produced by PowerShell are by default in Unicode (UTF16), if you need a different encoding, use Out-File instead of the redirection operator.

Examples

PS C:\> Get-ChildItem c:\windows\system >> "c:\my logs\text1.txt"

PS C:\> Get-ChildItem c:\windows\system | Out-File text2.txt -encoding ASCII

PS C:\> Start-Transcript -path c:\docs\Text3.txt
        ...
PS C:\> Stop-Transcript

“Most variables can show either an upward trend or a downward trend, depending on the base year chosen” ~ Thomas Sowell

Related PowerShell Cmdlets:

Out-Host - Send the pipelined output to the host.
Out-String - Send objects to the host as a series of strings.
Tee-Object - Send input objects to two places.
Start-Transcript - Start a transcript of a command shell session.
Stop-Transcript
- Stop the transcription process.


 
Copyright © SS64.com 1999-2019
Some rights reserved