Home ยป PowerShell ยป PowerShell -OutVariable Parameter

PowerShell -OutVariable Parameter

The PowerShell -OutVariable is a useful parameter that stores the output from the command in the specified variable, while also sending the output to the console. Using the outvariable allows for the storage of a command output, manipulation, and processing of the data.

Using the -OutVariable parameter, it stores the command output in a variable, to add another command output in the same variable, use a plus sign (+) before the variable name.

The variable created by OutVariable is of type [System.Collections.ArrayList]. Use the PowerShell GetType() cmdlet to check the type of the variable.

In this article, we will discuss how to use PowerShell -OutVariable parameter to store the command output.

PowerShell -OutVariable

Use the -OutVariable parameter to store the output of a command in a specified variable in addition to sending the output to the console or pipeline.

Get-ChildItem -Path D:\Logs\ -OutVariable logFiles

In the above PowerShell script, the Get-ChildItem cmdlet uses the Path variable to get the items from the specified location. PowerShell -OutVariable stores the Get-ChildItem command output in logFiles variable and also sends the output to the console.

The output of the above PowerShell script uses the -OutVariable parameter to store the output in logFiles and displays the output on the console as given below:

PowerShell -OutVariable - Store the output and print output
PowerShell -OutVariable โ€“ Store the output and print output

Use the โ€“OutputVariable parameter that stores the command output to print the output on the console.

$logFiles

In the above PowerShell script, the $logFiles variable displays the content of the $logFiles.

PowerShell OutVariable Parameter Output
PowerShell OutVariable Variable Output

To add the output of another command to the OutVariable variable, type plus sign (+) before the variable. It will add the output without replacing the existing output.

# Use plus sign before the variable to add the output

Get-Content -Path D:\Logs\Log3.txt -OutVariable +logFiles

# Print the output of the variable
$logFiles

In the above PowerShell script, the Get-Content cmdlet reads the file content and displays the output on the PowerShell terminal. The OutVariable parameter adds the output to the logFiles variable.

The output of the above PowerShell script is:

PowerShell OutVariable Variable Content
PowerShell OutVariable Variable Content

Conclusion

I hope the above article on how to use the PowerShell -OutVariable parameter to store the output of the command in addition to displaying the output on the console is helpful to you.

You can find more topics about PowerShell Active Directory commands and PowerShell basics on the ShellGeek home page.

Leave a Comment