How to add multiple values in the Hashtable using PowerShell?


Example

For example, we have a below-created hashtable.

PS C:\> $servicehash = @{Name='Spooler';State='Stopped';StartType='Automatic'}

PS C:\> $servicehash

Output

Name       Value
----       -----
Name       Spooler
StartType  Automatic
State      Stopped

We need to add multiple values to the Name Key. If we directly append the value to the key it will treat it as a string and we will not get the desired output. See the example below.

Example

PS C:\> $servicehash.Name += "Winrm"
PS C:\> $servicehash

Output

Name Value
----       -----
Name       SpoolerWinrm
StartType  Automatic
State      Stopped

So to add the multiple values, we first need to declare a key as an array but by doing so it will clear the previous value so we have to add the previous value as well to the array.

Example

PS C:\> $servicehash.Name = @()
PS C:\> $servicehash.Name += "Spooler"
PS C:\> $servicehash.Name += "Winrm"
PS C:\> $servicehash

Output

Name      Value
----      -----
Name      {Spooler, Winrm}
StartType Automatic
State Stopped
PS C:\> $servicehash.Name
Spooler
Winrm

Updated on: 30-Mar-2021

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements