PowerShell: How to Filter a Hash Table


You can use the following syntax to filter a hash table in PowerShell:

$keys = @($my_hash.Keys)

$keys | ForEach-Object {
    if ($_ -notmatch 'A000') {
        $my_hash.Remove($_)
    }
}

This particular example filters the hash table named $my_hash to only keep the elements where the key contains the pattern A000.

This syntax works by first creating an array named $keys that contains all of the keys from the hash table named $my_hash.

Then, we use ForEach-Object to loop through each key of the hash table and remove any elements where the key does not contain the pattern A000.

Note: This syntax modifies the hash table in-place.

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

Example: How to Filter a Hash Table in PowerShell

Suppose we create the following hash table named $my_hash:

$my_hash = [ordered]@{
  'A0001' = 24;
  'A0002' = 20;
  'A0003' = 14;
  'B0001' = 31;
  'B0002' = 9;
  'B0003' = 15;
  'A0007' = 22;
} 

We can use the following syntax to filter this hash table to only keep the elements where the key contains the value A000:

$keys = @($my_hash.Keys)

$keys | ForEach-Object {
    if ($_ -notmatch 'A000') {
        $my_hash.Remove($_)
    }
}

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

PowerShell filter hash table

Notice that the updated hash table only contains the elements where the key contains the value A000.

Feel free to specify any pattern that you’d like following the -notmatch operator to instead filter your hash table based on a different pattern.

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
PowerShell: How to Update Values in Hash Table

Leave a Reply