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:
1 |
Get-Process | Export-Csv c:\scripts\test.txt |
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:
1 |
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:
1 |
#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:
1 |
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:
1 2 |
PS C:\Documents and Settings\user> 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:
1 |
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.