Blog Post

#PowershellBasics: Write the output to a file.

,

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:tempServices.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:tempServices.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:tempServices.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:tempServices.csv -Delimiter '|'

Original post (opens in new tab)
View comments in original post (opens in new tab)

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating