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.

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 an IT veteran with over 25 years of experience, much of it spent as an IT infrastructure consultant specializing in Microsoft server technologies with an emphasis in automation and efficiency. He is a multi-year recipient of the Microsoft MVP Award in Windows PowerShell. He works today as an independent author, trainer and consultant. Jeff has written for numerous online sites and print publications, is a contributing editor at Petri.com, and a frequent speaker at technology conferences and user groups.

comments powered by Disqus
Most   Popular