PowerShell: How to Check if Hash Table Contains Specific Key


You can use the following basic syntax in PowerShell to check if a hash table contains a specific key:

$my_hashtable.ContainsKey('A0004')

This particular example checks if the hash table named $my_hashtable contains the key A0004.

This will return either True or False to indicate whether or not any element in the hash table contains the key.

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

Example: How to Check if Hash Table Contains Specific Key in PowerShell

Suppose we create the following hash table in PowerShell that contains keys that represent employee ID numbers and values that represent the employee names:

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

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

Suppose we would like to check if the employee ID number A0004 exists as a key in this hash table.

We can use the following syntax to do so:

$employees.ContainsKey('A0004')

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

PowerShell check if hash table contains key

This returns True since the employee ID number A0004 does indeed exist as a key in this hash table.

Suppose instead that we check if A0008 exists as as key in this hash table:

$employees.ContainsKey('A0008')

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

This returns False since the employee ID number A0008 does not exist as a key in this hash table.

Also note that you can use the -and operator to check if multiple specific keys exist in a hash table.

For example, we can use the following syntax to check if A0002 and A0006 both exist as keys:

$employees.ContainsKey('A0002') -and $employees.ContainsKey('A0006') 

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

PowerShell check if hash table contains multiple specific keys

This returns True since both A0002 and A0006 exist as keys in the hash table.

Note: You can find the complete documentation for the ContainsKey() method in PowerShell here.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: A Simple Formula for “Not Contains”
PowerShell: How to Check if File Contains Specific String
PowerShell: How to Replace Special Characters in String

Leave a Reply