There are several ways to capture the output of commands in PowerShell, as listed in Table 2-16.
Table 2-16. 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 = NativeCommand
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-OutVariablevariable
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 of the PowerShell or native command into File, overwriting File if it exists.
Command >> File 2>&1
Redirects both the error and standard output streams of the PowerShell or native command into File, appending to File if it exists.
You are currently reading a PREVIEW of this book.
Get instant access to over
$1 million worth of books and videos.