To format data as a table and then export data to a CSV file in PowerShell, you can use the Format-Table cmdlet followed by the ConvertFrom-Csv and Export-CSV cmdlets.
The following method shows how you can do it.
Method 1: Format table to csv file
$table = $data | Format-Table -AutoSize | Out-String
$table | ConvertFrom-Csv | Export-Csv -Path $csvFilePath -NoTypeInformation
This example will format the data as a table, and then export it to the CSV file.
The following example shows how you can use this method.
How to Format Data as Table to CSV in PowerShell
The following PowerShell syntax shows how you can do it.
# specify the csv file path $csvFilePath = "C:\temp\log\processData.csv" $data = @( [PSCustomObject] @{ "Name" = "Adam"; "Age" = 27 }, [PSCustomObject] @{ "Name" = "Gary"; "Age" = 38 } ) # Format the data as a table $table = $data | Format-Table -AutoSize | Out-String # Export the data to csv $table | ConvertFrom-Csv | Export-Csv -Path $csvFilePath -NoTypeInformation
In this script, we define a variable $csvFilePath to store the path of the csv file. The $data variable contains an array of objects with “Name” and “Age” properties.
We then format the data as a table and store it in the $table variable. The table data is piped to the ConvertFrom-Csv cmdlet to convert the formatted string to a CSV format. The Export-CSV cmdlet to export data to a CSV file at the specified path.
Conclusion
I hope the above article on how to format table to a CSV file using PowerShell is helpful to you.
You can find more topics about Active Directory tools and PowerShell basics on the ActiveDirectoryTools home page.