PowerShell: How to Remove Elements from a Hash Table


You can use the following methods to remove elements from a hash table in PowerShell:

Method 1: Remove Element by Name

$my_hash.Remove('A0005')

This particular example removes the element with a name of A0005 from the hash table named $my_hash.

Method 2: Remove Element Based on Condition

($my_hash.GetEnumerator() | ? {$_.Value -le 15}) | % {$my_hash.Remove($_.Name)}

This particular example removes all elements from the hash table named $my_hash where the Value is less than or equal to 15.

The following examples show how to use each method in practice.

Example 1: How to Remove Elements from Hash Table by Name

Suppose we create the following hash table in PowerShell that contains keys that represent employee ID numbers and values that represent the total sales made by each employee:

$employees = @{
  'A0001' = 24;
  'A0002' = 20;
  'A0003' = 14;
  'A0004' = 31;
  'A0005' = 9;
  'A0006' = 15;
  'A0007' = 22;
}

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

Suppose we would like to remove the element from the hash table where the key is equal to A0005.

We can use the following syntax to do so:

$employees.Remove('A0005')

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

PowerShell remove element from hash table by name

We can see that the element with a key equal to A0005 has been removed from the hash table while all other elements remain.

Example 2: How to Remove Elements from Hash Table Based on Condition

Once again, suppose we create the following hash table in PowerShell that contains keys that represent employee ID numbers and values that represent the total sales made by each employee:

$employees = @{
  'A0001' = 24;
  'A0002' = 20;
  'A0003' = 14;
  'A0004' = 31;
  'A0005' = 9;
  'A0006' = 15;
  'A0007' = 22;
}

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

Suppose we would like to remove all elements from the hash table where the Value is less than or equal to 15.

We can use the following syntax to do so:

($employees.GetEnumerator() | ? {$_.Value -le 15}) | % {$employees.Remove($_.Name)}

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

PowerShell remove elements from hash table based on condition

We can see that each of the elements with a Value less than or equal to 15 has been removed from the hash table.

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 Iterate Over a Hash Table
PowerShell: How to Convert Array to Comma Separated String

Leave a Reply