Capturing Output

There are several ways to capture the output of commands in PowerShell:

Capturing output in PowerShell

Command

Result

$variable = <Command>

Stores the objects produced by the PowerShell command into $variable.

$variable = <Command> | Out-String

Stores the visual representation of the PowerShell command into $variable. This is the PowerShell command after it’s been converted to human-readable output.

$variable = <Native Command>

Stores the (string) output of the native command into $variable. PowerShell stores this as a list of strings—one for each line of output from the native command.

<Command> -OutVariable variable

For most commands, stores the objects produced by the PowerShell command into $variable. The parameter -OutVariable can also be written -Ov

<Command> > <File>

Redirects the visual representation of the PowerShell (or standard output of a native command) into <File>, overwriting <File> if it exists. Errors are not captured by this redirection.

<Command> >> <File>

Redirects the visual representation of the PowerShell (or standard output of a native command) into <File>, appending to <File> if it exists. Errors are not captured by this redirection.

<Command> 2> <File>

Redirects the errors from the Powershell or native command into <File>, overwriting <File> if it exists.

<Command> 2>> <File>

Redirects the errors from the Powershell or native command into <File>, appending to <File> if it exists.

<Command> > <File> 2>&1

Redirects both the error and standard output streams ...

Get Windows PowerShell Quick Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.