PowerShell export data to CSV in proper format

33 views Asked by At

I get PSDrive information of my computer and put them into table format.

Get-PSDrive -Name C, D | 

Select-Object -Property Name,
@{Name="Total (GB)"; Expression={($_.Used + $_.Free) / 1gb}}, 
@{Name="Used (GB)"; Expression={$_.Used / 1gb}}, 
@{Name="Free (GB)"; Expression={$_.Free / 1gb}} |

Format-Table

Below is the output on PowerShell.

Name Total (GB) Used (GB) Free (GB)
---- ---------- --------- ---------
C        241.21    109.29    131.92
D        233.90      0.10    233.80

Finally I try to export data into CSV file with another pipe.

Export-Csv .\Desktop\CheckDrive.csv -Encoding utf8

I notice the data in CSV is very weird, it is totally different from the original data and not in the proper table format. Appreciate your help.

enter image description here

1

There are 1 answers

1
Milos Stojanovic On BEST ANSWER

Ok, so the problem is that you are trying to use Export-Csv, after Table-Format which doesn't return object that you need to export to csv. It returns format objects that represent table so it's not what you want. To fix it, remove Table-Format and directly pipe Select-Object to Export-Csv.

Table-Format output

This cmdlet returns format objects that represent the table.

This is what docs says about exporting to csv using Export-Csv:

The Export-CSV cmdlet creates a CSV file of the objects that you submit.
...
Do not format objects before sending them to the Export-CSV cmdlet. If Export-CSV receives formatted objects the CSV file contains the format properties rather than the object properties.