A common task when working with the command prompt is to write the output of commands to a file. As with cmd.exe, PowerShell supports the redirection of output but has more options. PowerShell also comes with a couple of cmdlets that support further features.

Wolfgang Sommergut

Wolfgang Sommergut has over 20 years of experience in IT journalism. He has also worked as a system administrator and as a tech consultant. Today he runs the German publication WindowsPro.de.

A common task when working with the command prompt is to write the output of commands to a file. As with cmd.exe, PowerShell supports the redirection of output but has more options. PowerShell also comes with a couple of cmdlets that support further features.

Whether you want to permanently save the output of complex calculations or log details of a script, you usually need a procedure to redirect the console output to a file. You can accomplish this job using redirect operators that work in a way that is similar to the conventional command prompt (at least as long as the task is relatively simple). If you just want to redirect the regular and successful output of a command to a file, the redirect operators “>” and “>>” are all you need:

If process.out already exists, PowerShell would overwrite the file’s previous contents, in contrast to the next example where the redirected output will be appended to the file:

Redirecting five output streams ^

In addition to the actual results, most cmdlets and scripts return further information such as errors, warnings, and status messages. If a script is supposed to return data through the appropriate streams, its programmer has to follow a few rules. In particular, this means that he has to use the suitable cmdlets to write the information to the right stream. For instance, Write-Debug, Write-Verbose, and Write-Warning are cmdlets that are typically used to deliver information about the command processing.

Whereas cmd.exe is only able to redirect error messages to an alternative device, PowerShell supports five different output types (streams):

  1. Success output
  2. Errors
  3. Warning messages
  4. Verbose output
  5. Debug messages

To redirect only a particular output type, you have to add the stream number to the redirect operator:

Like usual, this command would display a list of the running processes, whereas all debug information would be written to debug.out. If you want to append the file with debug data, you would use 5>> instead.

Redirecting to different streams ^

If you want to redirect to another stream instead of to a file, the redirect operator expects the following syntax:

“m” stands for the stream that you want to redirect, and “n” represents the target stream. For example, the following command redirects debug information to the regular output stream of Get-Process:

If you want to redirect not only a single stream but all streams, PowerShell allows you to work with wildcards:

This command redirects the contents of all five streams to process.out. The same command can be used with “>>” in order to append the data to the file. Redirecting all streams to a single stream is just as admissible:

Splitting output with tee ^

If you redirect the output of a command to a file, the data is no longer available in the pipeline to process it with another cmdlet. Sticking with the above example, if you want to write the entire output of Get-Process to a file and only display the attributes ID, Name, and CPU, the following command wouldn’t work:

In this case, nothing would arrive at Select and, accordingly, its output would be empty. The remedy for this is the Tee-Object cmdlet, which splits the output like its UNIX counterpart. This enables you to store the output in a file and process it on the console, where you can pass it through the pipeline to another cmdlet:

Splitting output with Tee-Object

Splitting output with Tee-Object

Using additional options with Out-File ^

In most cases, redirecting via “>” and “>>” proves to be sufficient to write the desired information to a file. However, these operators only allow you to overwrite or append files, and they don’t offer any options. In contrast, the Out-File cmdlet comes with a variety of additional features such as the ability to use another character set, work with an alternative line length, or store data in write-protected files. It accepts input through the pipeline or the -InputObject parameter:

This command writes the output of Get-Process to the file temp.out, uses the ASCII character set, and sets the line length to 256 characters to ensure that no information is lost in the table.

Because of the -Force parameter, Out-File would overwrite an existing file without warning even if the read-only attribute is set. If you want to append the output to a file, you have to use the -NoClobber parameter.

Alternatively, you can pass the output of Get-Process to Out-File through the pipeline:

Writing to multiple files ^

Because the redirect operators and Out-File don’t accept wildcards for file names, you can only use them to write to one file. This is usually sufficient when you only want to save the output of a command.

However, if you want to update the contents of multiple files, the cmdlets Set-Content and Add-Content are suitable for the task. The first one replaces the contents of the specified file, whereas the latter appends the data to the file.

Set-Content cannot modify existing text in the file; it creates new files with the contents that you pass through the -Value parameter. If you only want to replace distinct strings, you have to first read all files with Get-Content, process the contents with simple substitution patterns or regular expressions, and then write back the result with Set-Content.

However, it is easier if you only want to append information to existing files. In this case, you can pass one or more file names, separated by commas, through the parameter -Path. It is also possible to target several files with the help of wildcards. The parameter -Value takes the output of the corresponding cmdlet as input:

Join the 4sysops PowerShell group!

Your question was not answered? Ask in the forum!

1+

Users who have LIKED this post:

  • avatar
Share
5 Comments
  1. patricio 4 years ago

    please help-me:
    what it's wrong : ObjShell.Run ("powershell -executionpolicy bypass -noexit -file c:\temp\.\hola.ps1 hola | Out-File c:\temp\result3.txt")

    executing OK in CMD POwershell; but not returning file calling in VB6..
    Test
    01) file C:\temp\hola.ps1

    function Hola()
    {
    return "Hola como te va!"
    }

    02) executing cmd Powershell command prompt

    PS C:\temp> . .\hola.ps1
    PS C:\temp> hola
    Hola como te va!
    PS C:\temp>

    its OK!!!

    03) directioning output file
    executing cmd Powershell command prompt

    PS C:\temp> . .\hola.ps1
    PS C:\temp> hola | result2.txt
    PS C:\temp> hola | out-file result2.txt
    PS C:\temp>

    its OK!!!

    04) Call by Program VB6
    Dim ObjShell As Object
    Set ObjShell = CreateObject("WScript.shell")
    ObjShell.Run ("powershell -executionpolicy bypass -noexit -file c:\temp\.\hola.ps1 hola | Out-File c:\temp\result3.txt")

    Wrong.... It's Open Powershell :
    Windows PowerShell
    Copyright (C) 2013 Microsoft Corporation. Todos os direitos reservados.

    PS C:\VB6\Licencas>
    typing: hola returning:

    PS C:\VB6\Licencas> hola
    Hola como te va!
    PS C:\VB6\Licencas>
    Problem: it's not returning out-file c:\temp\result3.txt
    I try:
    ObjShell.Run ("powershell -executionpolicy bypass -noexit -file c:\temp\.\hola.ps1 & -command {hola} | Out-File c:\temp\result2.txt")
    and
    ObjShell.Run ("powershell -executionpolicy bypass -noexit -file c:\temp\.\hola.ps1 ;hola | Out-File c:\temp\result2.txt")
    and
    ObjShell.Run ("powershell -executionpolicy bypass -noexit -file c:\temp\.\hola.ps1 & CHR(34) & "" hola "" | Out-File c:\temp\result2.txt")
    but without success.....

    Thank you in advanced ..

    Patricio

    0

  2. Graham 4 years ago

    Excellent summary thanks

    Graham.

    0

  3. Freon 2 years ago

    What does "Cannot proceed with byte encoding. When using byte encoding the content must be of type byte." mean?

    0

  4. Luc Fullenwarth 9 months ago

    Thanks Wolfgang for your very good post.

    Just a little add-on:
    Currently, we can only redirect to stream 1 with the m>&n method.

    >&2 returns The operator is reserved for future use.

    and

    >&3 or anything else above 2 returns Missing file specification after redirection operator.

    0

  5. David Figueroa 9 months ago

    There is a mistake in the post relative to cmd.exe

    "Whereas cmd.exe is only able to redirect error messages to an alternative device"

    CMD.exe supports 3 streams.

    • 0 - Standard input
    • 1 - Standard output
    • 2 - Standard error

    The redirect operator works the same way between powershell & cmd.  You can redirect the output and error streams to files, or as Luc pointed out, you can use the 2>&1 to redirect the standard error stream into the same place as the standard output stream.  The key with the & operator is that it goes to the same place as the specified stream.

    David F.

    You can use the redirection to send something into the Standard Input stream that feeds into a command.

    0

Leave a reply

Your email address will not be published. Required fields are marked *

*

© 4sysops 2006 - 2019

CONTACT US

Please ask IT administration questions in the forums. Any other messages are welcome.

Sending

Log in with your credentials

or    

Forgot your details?

Create Account