#PowershellBasics: Write the output to a file.

1

July 14, 2022 by Kenneth Fisher

Last week I posted about a request to get a list of services. The first problem I ran into was expanding the column width, now I need to get the output off my screen and into a file to send the requestor. The cmdlet out-file is perfect for this and it’s pretty simple.

Get-Service | Where-Object {$_.Status -eq "Running"} | `
    Format-Table -AutoSize | Out-File -FilePath C:\temp\Services.txt

Fantastic! But what if I want a csv (comma delimited) format? In that case I can use Export-Csv.

This did take me a bit of work to figure out. I couldn’t just replace Out-File with Export-Csv. After a bunch of messing around it turned out that Format-Table, that I’d used to avoid data truncation was causing me a problem. Once I took that out it worked great.

Get-Service | Where-Object {$_.Status -eq "Running"} | `
    Export-Csv -Path C:\temp\Services.csv 

Interestingly it turns out that by using Export-Csv I no longer have a truncation issue, and I have a lot more columns. Some of which could be handy, but in this case I only wanted the three that I started with. So we throw in a Select-Object to specify the columns we want.

Get-Service | Where-Object {$_.Status -eq "Running"} | `
    Select-Object Status, Name, DisplayName | `
    Export-Csv -Path C:\temp\Services.csv

And there we go! Another useful feature of Export-Csv is that you can change the delimiter (by default the comma) to something else by just using the -Delimiter parameter. For example this gives us a pipe delimited file.

Get-Service | Where-Object {$_.Status -eq "Running"} | `
    Select-Object Status, Name, DisplayName | `
    Export-Csv -Path C:\temp\Services.csv -Delimiter '|'

One thought on “#PowershellBasics: Write the output to a file.

  1. […] Kenneth Fisher needs someplace to put all of his great ideas: […]

Leave a reply to Write Powershell Output to a File – Curated SQL Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Enter your email address to follow this blog and receive notifications of new posts by email.

Join 3,975 other subscribers

Follow me on Twitter

Archives

ToadWorld Pro of the Month November 2013