top of page

PowerShell Hash Tables

Using Hash Tables in PowerShell: A Guide with Examples

Hash tables in PowerShell are a powerful way to store and manage data. They consist of key-value pairs, where each key is unique, making data retrieval fast and efficient. Here's how you can use hash tables in PowerShell with practical examples:


Creating a Hash Table

To create a hash table, use the @{} syntax:

# Create an empty hash table

$hashTable = @{}

# Create a hash table with initial key-value pairs

$person = @{

Name = "John Doe"

Age = 30

Occupation = "Developer"


# Adding a new key-value pair

$person['City'] = 'New York'

# Modifying an existing key-value pair

$person['Age'] = 31


Accessing Values

Accessing values in a hash table is straightforward using the key:

# Accessing a value by its key

$name = $person['Name']

Write-Output $name

# Output: John Doe

# Using dot notation

$occupation = $person.Occupation

Write-Output $occupation

# Output: Developer

Removing Entries

Remove entries from a hash table using the Remove method or the Remove-Item 

# Remove an entry using Remove method


# Remove an entry using Remove-Item cmdlet

Remove-Item -Path $person['Occupation']

Enumerating Hash Table Entries

You can enumerate all key-value pairs in a hash table using a foreach loop:

foreach ($key in $person.Keys) { Write-Output "$key: $($person[$key])" }

Nested Hash Tables

Hash tables can contain other hash tables as values, allowing for more complex data structures:

# Creating a nested hash table

$employee = @{ Name = "Jane Smith"; Contact = @{ Email = ""; Phone = "555-1234" } }


# Accessing nested hash table values

$email = $employee.Contact.Email

Write-Output $email


Using Hash Tables to Create Custom Objects

Hash tables can be used to create custom objects, making data manipulation more intuitive:

# Create a custom object using a hash table

$customObject = [PSCustomObject]@{ FirstName = "Alice"; LastName = "Johnson"; Department = "IT" }

Write-Output $customObject

By mastering hash tables in PowerShell, you can enhance your scripts'

efficiency and readability, making data management tasks more streamlined

and effective.

#Set Values to Variable         
    $Hotfix = Get-Hotfix | Select -ExpandProperty HotfixID

    $Services = Get-Service | Where {$_.Status -eq "Running"} | Select -ExpandProperty Name

    $Enabled_Local_Accounts=Get-WmiObject -Class Win32_UserAccount -Filter {LocalAccount ='True' and Disabled='False'} | Select -ExpandProperty Name

    $Drives=Get-PSDrive | Where{$_.Free -ne $Null} | Select -ExpandProperty Name 

 #Creatre Hash and add Multiple Values 

    #Access Hash Data    

PowerShell Hash
bottom of page