PowerShell: How to Convert Hash Table to CSV


You can use the following syntax in PowerShell to convert a hash table to a CSV file:

$myhash.GetEnumerator() |
Select-Object -Property Key,Value |
Export-Csv employee_info.csv -NoTypeInformation

This particular example converts the hash table named $myhash to a CSV file named employee_info.csv.

The following example shows how to use this syntax in practice.

Example: How to Convert Hash Table to CSV File Using PowerShell

Suppose we create the following hash table in PowerShell named $employees:

$employees = @{
  A0001 = 'Andy';
  A0002 = 'Bob';
  A0003 = 'Chad';
  A0004 = 'Derrick';
  A0005 = 'Erin';
  A0006 = 'Frank';
  A0007 = 'Greg';
}

The following screenshot shows how to use this syntax in practice:

Suppose that we would like to convert this hash table to a CSV file with two columns, one for the keys and one for the values.

We can use the following syntax to do so:

$employees.GetEnumerator() |
Select-Object -Property Key,Value |
Export-Csv employee_info.csv -NoTypeInformation

The following screenshot shows how to use this syntax in practice:

PowerShell convert hash table to CSV

If we navigate to the current directory where we exported the employee_info.csv file, we can view the contents of the file:

Notice that the CSV file contains two columns: one for the keys of the hash table and another for the values.

Note #1: If we didn’t include the line Select-Object -Property Key, Value then there would have been an extra column at the beginning of the CSV file that contained duplicate values of the keys in the hash table.

Note #2: We included -NoTypeInformation to specify that no #TYPE information should be included as the first row in the exported CSV file.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Check if Hash Table Contains Specific Key
PowerShell: How to Remove Elements from a Hash Table
PowerShell: How to Iterate Over a Hash Table

Leave a Reply