Controlling PowerShell's Results with Out-File

PowerShell Writes to Text File with: Out-File

Viewing a script's output on screen is all well and good, but it's often more convenient tell PowerShell to write the output into a text file.  This a task for Out-File.

Here we have a PowerShell instruction that you simply bolt-on to an existing script. ..... | Out-File "Filename.txt".  Incidentally, the simplicity of Out-File is one reason to employ PowerShell instead of VBScript.

Topics for PowerShell Output to File

 ♣

Introduction to Out-File

Writing the results of a command into a file is easy with PowerShell's Out-File.  The biggest danger is 'over-think'; just remember that PowerShell takes care of basic file operations automatically.  Consequently, there is no need to waste time looking for non-existent open-file, or save-file commands.  If the file specified by Out-File does not already exist, PowerShell even creates it for you.

This cmdlet works deceptively simply; assuming the first part of the script delivers the results, just redirect the output to a file with a command such as:
... main PowerShell command | Out-File C:\ logs\result1.txt.

Example 1 - Starting with Out-File

This example is designed to concentrate on the Out-File command.  In fact, the sooner we move on to example 2, the sooner we can do some real work.

# PowerShell write to text file
Get-ChildItem "C:\Windows\System32" | Out-File "D:\Files\Sys32.txt"

Note 1:  While Out-File creates the file, you have to make sure that the path exists because Out-File cannot create folders.  In this instance, you may wish to change D: \Files to an existing folder on your machine.

Example 2 - Putting Out-File to Work

This example has extra features, which make the script more useful.  Thanks to the -recurse parameter, the script is designed to drill down into the subdirectories.  The question mark '?' introduces a 'Where-Object' statement, its purpose is to filter just the dll files.  In this example the output contains only the two file properties that we are interested in: Name and CreationTime.

# PowerShell script to list the dll files under C:\Windows\System32
$DllFiles = gci "C:\Windows\System32" -recurse | ? {$_.extension -eq ".dll"} |
Format-Table Name, CreationTime -auto | Out-File -filepath "D:\Files\dll.txt"
$DllFiles

Note 3: The parameter -filepath is optional.  If you omit -filepath, PowerShell's intelligence deduces from the sequence of commands that "D:\Files\dll.txt" is the place to save the file.  If there are no spaces in the path, then you can even omit the speech marks.

Note 4: If you get an error message 'Cannot find part of the path', then amend D: \Files to a real folder on your machine.

Note 5: I try not use the backtick symbol `, instead I ended line 2 with the | pipe symbol.. As a result PowerShell realizes that the command continues on the next line.

Improvements:

  1. You could amend gci "C:\Windows\System32" -Recurse -ErrorAction SilentlyContinue
  2. If could be useful to append: Invoke-Item "D:\Files\dll.txt"

Guy Recommends:  A Free Trial of the Network Performance Monitor (NPM)Review of Orion NPM v10

SolarWinds' Network Performance Monitor will help you discover what's happening on your network.  This utility will also guide you through troubleshooting; the dashboard will indicate whether the root cause is a broken link, faulty equipment or resource overload.

What I like best is the way NPM suggests solutions to network problems.  Its also has the ability to monitor the health of individual VMware virtual machines.  If you are interested in troubleshooting, and creating network maps, then I recommend that you try NPM now.

Download a free trial of Solarwinds' Network Performance Monitor

Research Out-File With Get-Help

Once I get a command to work, and I like it, I want to know more.  Get-Help always reveals at least one parameter that I had taken for granted, forgotten, or previously overlooked, so it is with PowerShell's write to text file.

Clear-Host
Get-Help Out-File -full

Note 2: Help Out-File -full also works.  Be aware that there is no need for a pipe (|) with help.

If you append the -full switch, then PowerShell's help reveals useful parameters, for example, -filepath (taken for granted) -Append (forgotten) -NoClobber (previously overlooked).

See more examples of PowerShell's output to file »

Example 3 - More Parameters (-Append and -NoClobber)

If you run the script for a second time, have you noticed how Out-File over-writes information?  If your intention was to add data at the end of the file, then one solution would be to replace Out-File with add-Content.   However, because of the superior formatting, I prefer to stick with Out-File and add the -Append parameter.

PowerShell Out-File -Append

Out-File can be vicious in that it overwrites the file.  Fortunately, Out-File has the -Append parameter so that you can just add the data to the end of existing entries.

# PowerShell Out-File -Append
$File ="C:\PowerShell\Processes.txt"
Get-Date | Out-File $File
Get-Process | Out-File $File -Append

Note 6: You could add another -Append to the end of the Get-Date line.

Another -Append Example

| Out-File -Filepath "D:\Files\dll.txt"  -Append

PowerShell -NoClobber

What can 'No Clobber' mean?  Lost your clothes?  Not so, NoClobber means don't over-write the file.  It seems to me that you would incorporate the -NoClobber in circumstances where your intention was to save lots of files with slightly different names, and you did not want to risk losing their contents by over-writing.

| Out-File -filepath "D:\Files\dll June.txt"  -NoClobber

Note 7:  If you insist on running the script again, the -NoClobber parameter causes PowerShell to generate an error message and thus protects the original file from being replaced.

Invoke-Item is a Useful Technique

# PowerShell Out-File -Append
$File ="C:\PowerShell\Processes.txt"
Get-Date | Out-File $File
Get-Process | Out-File $File -Append
Invoke-Item $File

See more on Invoke-Item »

PowerShell's Content Family

Out-File is an honorary member of the 'Content' family, here are the cousin commands.  I don't often use these other commands because they don't format the data as I would like.

Add-Content (Appends)
Clear-Content
Get-Content
Set-Content (Replaces existing content)

Out-Printer Cmdlet

Out-File has a sister command called out-Printer.  If you try:
Help out-Printer

Then you can see that you don't need to specify the name of the printer, PowerShell automatically selects the default printer, just as you would print from any other application.

You could experiment by substituting out-Printer for any of the above Out-File commands

Out-GridView

With PowerShell v 2.0 you can output to a GridView.

Export-Csv also Import-Csv

Spreadsheets are a convenient vehicle for importing and exporting objects into Active Directory.  Begin by appending  export-Csv to QAD scripts which list users or computers.

Guy Recommends:  SolarWinds' Free Bulk Import ToolFree Download Solarwinds Bulk Import Tool

Import users from a spreadsheet.  Just provide a list of the users with their fields in the top row, and save as .csv file.  Then launch this FREE utility and match your fields with AD's attributes, click and import the users.

Optionally, you can provide the name of the OU where the new accounts will be born. Download your FREE bulk import tool.

If you need more comprehensive application analysis software,
Download a free trial of SAM (Server & Application Monitor)

A Different Technique: PowerShell Redirection

In many ways this is the simplest technique yet.  Just append the greater than sign >.  However, the killer reason for redirecting the output of a PowerShell command is when you want to record error messages or warnings.

Get-Service > D:\PShell\Services.txt

Note 8: This is the same as Get-Service | Out-File D:\PShell\Services.txt

The killer reason for using this technique is if you want to redirect warning messages, for instance you want to see if a service jkl exists:

Get-Service jkl 2> D:\PShell\Services.txt

Note 9: The key redirect command is 2>

See more On PowerShell 3.0 Redirection »

Summary of PowerShell's Out-File Cmdlet

Trust me; you will make great use of the ability of PowerShell to write to text file.  Out-File is the perfect command for piping the results to a text file.  This is a straight-forward command to bolt-on to existing cmdlets.  The main danger for newbies is looking for non-existent commands; remember that PowerShell takes care of both opening and closing the named file.

Footnote:
Thanks to Danny Beaman for correcting 3 errors on this page.

If you like this page then please share it with your friends

 


See more Microsoft PowerShell file tutorials:

PowerShell Home   • Add-Content   • Get-Content   • Set-Content  • PowerShell -Filter   • Test-Path

PowerShell Get-ChildItem   • Get-ChildItem -Include   • Get-ChildItem -Exclude   • Compare-Object

PowerShell Registry  • Get-Credential  • PowerShell ItemProperty  • PowerShell ItemPropery GCI

Please email me if you have a better example script. Also please report any factual mistakes, grammatical errors or broken links, I will be happy to correct the fault.

 

 *


Custom Search

Site Home

Guy Recommends: WMI Monitor for PowershellSolarwinds WMI Monitor

Windows Management Instrumentation (WMI) is most useful for PowerShell scripting.

SolarWinds have produced this Free WMI Monitor to take the guess work out of which WMI counters to use for applications like Microsoft Active Directory, SQL or Exchange Server.

Download your free copy of WMI Monitor

Author: Guy Thomas Copyright © 1999-2014 Computer Performance LTD All rights reserved.

Please report a broken link, or an error to: