Output from a specific stream may be directed by placing the stream number on the left of the redirect operator.
For example, the output written by Write-Warning can be directed to a file:
PS> function Test-Redirect{
'This is standard out'
Write-Warning 'This is a warning'
}
$stdOut = Test-Redirect 3> 'warnings.txt'
Get-Content 'warnings.txt'
This is a warning
When using the redirect operator, any file of the same name is overwritten. If information must be added to a file, the operator becomes >>:
$i = 1 function Test-Redirect{ Write-Warning "Warning $i" } Test-Redirect 3> 'warnings.txt' # Overwrite $i++ Test-Redirect 3>> 'warnings.txt' # Append
It is possible to redirect additional streams, for example, warnings and errors, by adding more redirect statements. The following example redirects the error and warning streams to separate files:
function Test-Redirect{ 'This is standard out' Write-Error 'This is an error' Write-Warning 'This is a warning' } Test-Redirect 3> 'warnings.txt' 2> 'errors.txt'
The wildcard character * may be used to represent all streams if all content were to be sent to a single file:
$verbosePreference = 'continue' function Test-Redirect{ 'This is standard out' Write-Information 'This is information' Write-Host 'This is information as well' Write-Error 'This is an error' Write-Verbose 'This is verbose' Write-Warning 'This is a warning' } Test-Redirect *> 'alloutput.txt'
The preceding example starts by setting the verbose preference variable. Without this, the output from Write-Verbose will not be shown at all.