Skip to content

Commit 4caa1de

Browse files
committed
feat(function): Create function that checks for the existence of a specific key within a hash table.
1 parent 311a872 commit 4caa1de

File tree

2 files changed

+71
-7
lines changed

2 files changed

+71
-7
lines changed
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
function Test-HashTableKeyExistence {
2+
<#
3+
.SYNOPSIS
4+
Check if a key exists in a hash table.
5+
6+
.DESCRIPTION
7+
This function checks whether a specified key exists in a hash table, even if the associated value is $null.
8+
9+
.PARAMETER HashTable
10+
The hash table to check. Accepts input from the pipeline.
11+
12+
.PARAMETER KeyToCheck
13+
The key to check for existence in the hash table.
14+
15+
.INPUTS
16+
Hashtable: accepts hashtable object from the pipeline.
17+
String: accepts key name as a string.
18+
19+
.OUTPUTS
20+
Boolean: Returns true if the key exists, false otherwise.
21+
22+
.EXAMPLE
23+
$HashTable = @{
24+
Key1 = 'Value1'
25+
Key2 = $null # Note: this key exists but has null value
26+
Key3 = 'Value3'
27+
}
28+
Test-HashTableKeyExistence -HashTable $HashTable -KeyToCheck 'Key2'
29+
30+
Tests if 'Key2' exists in the provided hash table.
31+
32+
.EXAMPLE
33+
$HashTable = @{
34+
KeyA = 'ValueA'
35+
KeyB = 'ValueB'
36+
}
37+
38+
$HashTable | Test-HashTableKeyExistence -KeyToCheck 'KeyC'
39+
40+
Tests if 'KeyC' exists in the provided hash table.
41+
42+
.NOTES
43+
Author: Sam Erde
44+
Version: 1.0
45+
Date: 2026-01-05
46+
#>
47+
[CmdletBinding()]
48+
[OutputType([bool])]
49+
param (
50+
51+
# The hash table object to check.
52+
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
53+
[ValidateNotNull()]
54+
[hashtable]$HashTable,
55+
56+
# The name of the key to check.
57+
[Parameter(Mandatory = $true)]
58+
[ValidateNotNullOrEmpty()]
59+
[string]$KeyToCheck
60+
)
61+
62+
process {
63+
if ($HashTable.ContainsKey($KeyToCheck)) {
64+
Write-Verbose "The key [$KeyToCheck] exists in the hash table."
65+
$true
66+
} else {
67+
Write-Verbose "The key [$KeyToCheck] does not exist in the hash table."
68+
$false
69+
}
70+
}
71+
}

Snippets/Check if a key exists in a hash table.ps1

Lines changed: 0 additions & 7 deletions
This file was deleted.

0 commit comments

Comments
 (0)