PowerShell: How to Convert Hash Table to String


You can use the following methods in PowerShell to convert a hash table to a string:

Method 1: Convert Hash Table Keys to String

[string[]]$keys_string = $employees.Keys

This particular example converts all of the keys in the hash table named $employees to a string.

Method 2: Convert Hash Table Values to String

[string[]]$values_string = $employees.Values

This particular example converts all of the values in the hash table named $employees to a string.

Method 3: Convert Hash Table Elements to String

[string[]]$elements_string = ($employees | Out-String -Stream) -ne '' | Select -Skip 2

This particular example converts all of the elements in the hash table named $employees to a string.

The following examples show how to use each method in practice with the following hash table named $employees:

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

Example 1: Convert Hash Table Keys to String

We can use the following syntax to convert only the hash table keys to a string:

[string[]]$keys_string = $employees.Keys

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

PowerShell convert hash table keys to string

Notice that all of the keys from the hash table have been converted into a single string named $keys_string.

Note: You can verify that $keys_string is indeed a string by typing $keys_string.GetType().

Example 2: Convert Hash Table Values to String

We can use the following syntax to convert only the hash table values to a string:

[string[]]$values_string = $employees.Values

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

PowerShell convert hash table values to string

Notice that all of the values from the hash table have been converted into a single string named $values_string.

Example 3: Convert Hash Table Elements to String

We can use the following syntax to convert all of the hash table elements to a string:

[string[]]$elements_string = ($employees | Out-String -Stream) -ne '' | Select -Skip 2

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

PowerShell convert hash table to string

Notice that all of the elements from the hash table have been converted into a single string named $elements_string.

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