Common/Public/Test-HashtableKeys.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
function Test-HashtableKeys
{
    param (
        [Parameter(Mandatory)]
        [hashtable]$Hashtable,

        [string[]]$MandatoryKeys,

        [string[]]$ValidKeys,

        [switch]$Quiet
    )

    $result = $true
    
    if ($ValidKeys)
    {
        $compareResult = Compare-Object -ReferenceObject $ValidKeys -DifferenceObject ([array]$Hashtable.Keys) | Where-Object SideIndicator -eq '=>'
        if ($compareResult -and -not $Quiet)
        {
            Write-Error "The keys '$($compareResult.InputObject -join ', ')' are not valid"
        }

        $result = -not $compareResult
    }

    if ($MandatoryKeys)
    {
        $compareResult = Compare-Object -ReferenceObject $MandatoryKeys -DifferenceObject ([array]$Hashtable.Keys) | Where-Object SideIndicator -eq '<='
        if ($compareResult -and -not $Quiet)
        {
            Write-Error "The keys '$($compareResult.InputObject -join ', ')' are mandatory and not defined"
        }

        $result = -not $compareResult
    }

    $result
}