# Contains-Hashtable.ps1
# Hashtable Contains method sample using PowerShell
# Thomas Lee - tfl@psp.co.uk
# Create and populate the hash table
$myht = @{}
$myht.Add( 0, "zero" );
$myht.Add( 1, "one" );
$myht.Add( 2, "two" );
# or a more powershell way
$myht += @{"3"= "three"}
$myht += @{"4"="four" }
# Display the values of the Hashtable
"The Hashtable contains the following values:"
$myht
""
# Use contains method
$myKey = 0;
"The key `"{0}`" is in the hashtable: {1}" -f $myKey, $myHT.Contains( $myKey )
$myKey = 5;
"The key `"{0}`" is in the hashtable: {1}" -f $myKey, $myHT.Contains( $myKey )
""
# Use containskey method
$myKey = 2;
"The key `"{0}`" is in the hashtable: {1}" -f $myKey, $myHT.ContainsKey( $myKey )
$myKey = 6;
"The key `"{0}`" is in the hashtable: {1}" -f $myKey, $myHT.ContainsKey( $myKey )
""
# Search for a specific value.
$myValue = "three";
"The value `"{0}`" is in the hash table: {1}" -f $myValue, $myHT.ContainsValue( $myValue )
$myValue = "nine";
"The value `"{0}`" is in the hash table: {1}" -f $myValue, $myHT.ContainsValue( $myValue )
This script produces the following output:
PSH [D:\foo]: .\contains-hashtable.ps1
The Hashtable contains the following values:
Name Value
---- -----
4 four
0 zero
2 two
1 one
3 three
The key "0" is in the hashtable: True
The key "5" is in the hashtable: False
The key "2" is in the hashtable: True
The key "6" is in the hashtable: False
The value "three" is in the hash table: True
The value "nine" is in the hash table: False