Save Output From a Powershell Command to a Variable

This article discusses two ways of saving PowerShell output into a variable. In each method, we will work on examples to cement the ideas.

Method 1: Using the Assignment Operator (=)

The most common way to save the output of a PowerShell command into a variable is using:

Now, you can use the $var variable to perform further operations on the output of the <command>.

Note: when the <command> runs successfully without an error, the output is sent to the success stream (stream #1), and if the <command> execution ends in error, the result is streamed to the error stream (stream #2).

In the $var = <command> line, the $var variable only picks data from the success stream (not error steam). In the example below, Get-ChildItem attempts to get child items from a folder that doesn’t exist, leading to an error. Notice that the variable $var2 does not pick the error; instead, the error output is sent to the console.

If you want also to pick the error output on the variable, use the following line to redirect the output.

The 2>&1 means we want to redirect the content of the error stream (Stream #2) to the success stream (Stream #1), which can now be stored on the variable.

The example above shows that the error message has now been captured in the variable $var2.

Note: the redirection command given above only works from within PowerShell. If you run an external command, you may need to modify the command slightly – enclose 2>&1 in quotes, that is

For example, the following command runs the dir using cmd.exe (not PowerShell).

The assignment operator can also be used with chained commands, as shown below. In this case, the output of <command-3> is saved on the $var

Example:

Method 2: Using the -OutVariable or -Ov Parameter

Note that in Method 1, when a variable captures command output, the output is not printed to the console unless you run the variable name as a command.

This is where this method comes in. The -OutVariable parameter allows us to save the data in a variable while letting it get printed on the console.

You can capture the output to a variable using the following syntax:

For chained commands, you will use this

For example,

The code above takes the “Hello World” string, gets its length, and saves the output on the $var5 variable.

Conclusion

This guide discussed two methods for saving PowerShell output into a variable. The first method uses the assignment operator (=), and the second method uses the -OutVariable parameter. In most cases, Method 1 does the job. The second method is handy if you want to save your data in a variable while still letting it get printed on the console.