Using the Export-Csv Cmdlet

Saving Data as a Comma-Separated Values File

The Export-Csv cmdlet makes it easy to export data as a comma-separated values (CSV) file; all you need to do is call Export-Csv followed by the path to the CSV file. For example, this command uses Get-Process to grab information about all the processes running on the computer, then uses Export-Csv to write that data to a file named C:\Scripts\Test.txt:

Get-Process | Export-Csv c:\scripts\test.txt

The resulting text file will look something like this:

#TYPE System.Diagnostics.Process
ExitCode,HasExited,ExitTime,Handle,HandleCount, Id,MachineName,MainWindowHandle,MainWindowTitle,MainModule,
NonpagedSystemMemorySize64, PagedMemorySize,PagedMemorySize64,PagedSystemMemorySize,PagedSystemMemorySize64,PeakPagedMemorySize,
PeakPagedMemorySize64,PeakWorkingSet,PeakWorkingSet64, PeakVirtualMemorySize,PeakVirtualMemorySize64,
ProcessorAffinity, Responding,SessionId,StartInfo,StartTime,SynchronizingObject,
Process,alg,110,33714176,3698688,1273856,5400,C:\WINDOWS\System32\alg.exe,"Microsoft Corporation",0.046875, 
"5.1.2600.2180 (xpsp_sp2_rtm.040803-2158)",5.1.2600.2180,"Application Layer Gateway Service",
"Microsoft? Windows? Operating System",8,,False,,2140,110,788,.,0,,"System.Diagnostics.ProcessModule 
System.Diagnostics.ProcessStartInfo,"5/19/2006 7:37:03 AM",,System.Diagnostics.ProcessThreadCollection,

By default, data is saved in ASCII format. What if you’d prefer to save the data in Unicode format (or maybe UTF7 or UTF8)? No problem; just add the -encoding parameter followed by the desired format:

Get-Process | Export-Csv c:\scripts\test.txt -encoding "unicode"

You might have noticed that the first line in the resulting CSV file lists the .NET object type:

#TYPE System.Diagnostics.Process

If you’d just as soon not have the .NET object type in your output file then simply include the -notype parameter:

Get-Process | Export-Csv c:\scripts\test.txt -notype

Another parameter you might find useful is -force. Suppose Test.txt is a read-only file: that enables people to access, but not change, the contents of the file. That’s great, until it comes time to use Export-Csv and update the contents of the file. Here’s what happens if you try to export text to a read-only file:

PS C:\Documents and Settings\gstemp> Get-Process | Export-Csv c:\scripts\test.txt
Export-Csv : Access to the path 'C:\scripts\test.txt' is denied.

That’s where -force comes into play. Suppose you add -force to your export command:

Get-Process | Export-Csv c:\scripts\test.txt -force

In that case, Windows PowerShell will temporarily clear the read-only attribute from the file, update the contents, and then reset the read-only attribute. The end result: the file gets updated, but when Export-Csv is finished the file will still be marked as read-only.

Export-Csv Aliases
  • epcsv