Prof. Powershell
Are You Content?
You may be familiar with Out-File for saving output to a file. Now, try something different and use Set-Content.
- By Jeffery Hicks
- 05/26/2009
Often when you run a PowerShell command you want to save the output to a file. But the technique to use may vary depending on what you need to do with that file. I've written in the past about the Out-File cmdlet. This will redirect any console output to a text file:
PS C:\dir | out-file dirlist.txt
You can also append and specify the encoding. Remember that Out-File will use Unicode by default which may cause issues depending on how you need to use the file later.
The contents of dirlist.txt will be the same as what you would have seen in the console. There are cmdlets you can use to create text files. Try this:
PS C:\ dir | set-content dirlist.txt
Look at dirlist.txt. Not what you expected is it? Set-Content takes the objects from Get-Eventlog and writes them to a file. In this particular example it is smart enough to only capture the name property. But look here:
PS C:\ get-service | set-content services.txt
Services.txt has the name of each object that was piped in. You can get around this by using:
PS C:\ get-service | out-string | set-content services.txt
which converts the objects to string objects which are then written to Set-Content. I think you'll have better success with Set-Content when working with existing text files. By the way, Set-Content uses ANSI encoding and that may make a difference, again, depending on what you might need to do later with the file.
Let's say you have a list of shares in a text file that you often work with. A server name has changed from FA123 to FZ456. You want to change the file:
PS C:\> (get-content shares.txt) | foreach {$_.replace("FA123","FZ456")} | set-content shares.txt
You have to put the first command in parentheses to instruct PowerShell to execute it. Otherwise, the file will be open when Set-Content tries to write to it and the command will fail.
Set-Content always creates a new file. If you want to append data, then use its brother cmdlet Add-Content.
About the Author
Jeffery Hicks is a Microsoft MVP and an IT veteran with almost 20 years of experience, much of it spent as an IT consultant specializing in Windows server technologies. He works today as an independent author, trainer and consultant. His latest book is Managing Active Directory with Windows PowerShell 2.0: TFM (SAPIEN Press 2011). Follow Jeff on Twitter and on his blog.