How-to: Redirection

  Redirection operators:

     >    Redirect to a file and replace contents.
     >>   Redirect to a file and append to existing content.
     >&1  Merge with pipeline output.

  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.

  Run command-2 only if command-1 succeeds:
  command-1; if ($LASTEXITCODE -eq 0) { command-2 }

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     # Append all streams (output, error, warning, verbose, and debug) to out.txt

To capture errors thrown by the environment rather than the cmdlet, run the cmdlet in a nested context, e.g. a script or scriptblock and redirect the output:

& { Get-ChildItem | select -expandProperty FullName } > filelist.txt 2> error.txt

In all cases the desired filename can be provided using a variable, for example:
$myLogFile = 'C:\scriptlogs\output.txt'
Get-ChildItem > $myLogFile

Numeric handles:

STDOUT = 1  Text output
STDERR = 2  Error text output
WARNING = 3 Warning output
VERBOSE = 4 Verbose output
DEBUG  = 5 Debug output
INFO   = 6 Information output (PowerShell 5.0+)

When redirection is performed without specifying a numeric handle, the default is 1, i.e. '>' will not redirect error messages.

In PowerShell 5.0+ an Error stream 6 was added for information, it is also used for the Write-Host output.
This means that Write-Host output can be supressed by redirecting 6>

You can direct these different output streams into separate files, for example:
Get-ChildItem >output.txt 2>errors.txt

Alternatively redirect the output stream(s) to a variable, for example:
$normal_and_error_output = $(New-Item c:\temp) 2>&1

To redirect all output streams use *> or to append *>>

New-Item c:\temp *>> 'C:\scriptlogs\output.txt'

Suppress all output from a command:

[void](New-Item c:\temp)

Error Streams

There are still some cmdlets which send error messages directly to the host, bypassing all of the error streams. These can not be redirected. This is because they are asking the user a question such as 'are you sure you want to remove this item', if such questions are redirected to a file the session will appear to hang while it waits for a response to a question the user can’t see.

  command 6>$null

Multiple redirections can be done on one line, so to redirect error and warning messages to null:

  command 2>$null 3>$null

Handling NULLs

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.

Raw .Net method calls are a special case, to redirect them, place in a scriptblock then use & (CALL) and redirect any errors to $null:

& {[System.Math]::Sqrt('notanumber')} 2>$null

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

Preference Variables - Determine which commands will produce output (Output streams 1 - 6).
Out-Host - Send the pipelined output to the host.
Out-String - Send objects to the host as a series of strings.
Write-Host - Display text on screen (does not wrap lines).
Tee-Object - Send input objects to two places.
Out-Default - Set the destination of default output, use this to redirect commands that write directly to the console, bypassing all streams.
Start-Transcript - Start a transcript of a command shell session.
Stop-Transcript
- Stop the transcription process.
Windows CMD equivalent: Redirection in CMD


 
Copyright © 1999-2024 SS64.com
Some rights reserved