Redirection to a file

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'
>> }
PS> $stdOut = Test-Redirect 3> 'warnings.txt'
PS> 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 was 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 verbosePreference variable. Without this, or the addition of the verbose parameter to the Write-Verbose command, the output from Write-Verbose will not be shown at all.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.236.174