Prof. Powershell

On File

Saving results of commands or queries to a file is easy with this PowerShell cmdlet.

A common administrative task is to save the results of a command or query to a text file. In the CMD shell the traditional method is to use the console redirection characters > and >>. You can still use these operators in PowerShell:

PS C:\> get-process > processes.txt

There's nothing wrong with this technique in PowerShell. I have yet to find a situation where it doesn't work.

But PowerShell has a cmdlet called Out-File which offers a bit more flexibility. This cmdlet should be at the end of your pipelined expression:

PS C:\> get-process | where {$_.workingset -gt 10mb} | out-file LargeProc.txt

Used without any parameters, Out-File will overwrite any existing file with the same name. The cmdlet includes an -append parameter which will give you the same result as if you had used the >> redirection operators.

However, the cmdlet also has a nice feature to keep you from accidentally overwriting a file. You can use the -NoClobber parameter:

PS C:\> get-process | where {$_.workingset -gt 10mb} | out-file LargeProc.txt -noclobber

When you use this parameter, if the file already exists PowerShell will display an error message:

Out-File : File C:\LargeProc.txt already exists and NoClobber was specified.

The cmdlet also supports the -whatIf and -Confirm parameters. These are also great "sanity-checkers."

By the way, you don't have to rely on the pipeline to use Out-File. You can use its -InputObject parameter which will take the specified object and send it to a file:

PS C:\> $p = get-process
PS C:\> out-file myprocs.txt -input $p

Finally, depending on your situation or the expression, Out-File supports several encoding schemes. Use the -Encoding parameter. The default is Unicode, but you can choose from ASCII, OEM, Default, BigEndianUnicode, UTF7, UTF8, and UTF32.

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

SharePoint Watch

Sign up for our newsletter.

I agree to this site's Privacy Policy.