Home » PowerShell » Write PowerShell Variable to File

Write PowerShell Variable to File

PowerShell variables can store values of different types of data, such as strings, objects, and numbers. Saving PowerShell variables to file can help with logging, and sharing data between scripts.

PowerShell has multiple cmdlets like Out-File, Set-Content, and Add-Content that allow you to write PowerShell variables to a file.

In this article, we will discuss how to write variables to files in PowerShell.

Using Out-File to Write Variable to a File in PowerShell

The Out-File cmdlet in PowerShell is used to send the output of a command or variable to a file. It saves the contents of a variable to a text file.

$userName = "Hello, I am ShellAdmin!"
$userName | Out-File -FilePath "greetings.txt"

In the above PowerShell script, the $username variable store the data of string type. The variable content passes through the pipeline operator the Out-File cmdlet to write its content to a file specified by the -FilePath parameter.

To check and verify the content of the variable in a text file, open the file using the Get-Content cmdlet in PowerShell.

Get-Content -Path "greetings.txt"

The output of the above PowerShell script displays the content of a variable.

Use Set-Content to Save Variable to File

Use the Set-Content cmdlet in PowerShell to save variable values to the file.

$userName = "Hello, I am ShellAdmin!"

Set-Content -Path "greetings.txt" -Value $userName

In the above PowerShell script, the Set-Content cmdlet uses the Path parameter to create file greetings.txt if not exist and write variable content to a file.

To verify the content of a variable in a text file, use the Get-Content cmdlet.

Get-Content -Path "greetings.txt"

Cool Tip: How to use PowerShell variable in Command!

Use Add-Content to Append Variable to a File

The Add-Content cmdlet in PowerShell adds or appends content to a file.

$userName = "Hello, I am ShellAdmin!"

Add-Content -Path "greetings.txt" -Value $userName

In the above PowerShell script, the Add-Content cmdlet writes the variable value to a file. If the file exists in the specified location, it doesn’t overwrite the file. It appends the data to a file.

You can use the Get-Content cmdlet in PowerShell to read the content of the file and verify the variable value stored in the file.

Cool Tip: How to use JSON data in PowerShell!


I hope the above article on how to save the variable to a file in PowerShell using different cmdlets is helpful to you.

Saving and retrieving variables content can be useful for logging script output, sharing data between scripts, and storing the configuration settings.

In PowerShell, you can export variables to file formats like CSV, XML, and JSON using the Export-Csv, Export-Clixml, and ConvertTo-Json cmdlets.

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

Leave a Comment