internal/functions/get-hashtablekey.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
41
42
43
44
45
46
47
48
49
50
51

<#
    .SYNOPSIS
        Get key from HashTable
         
    .DESCRIPTION
        Get specific key(s) from a HashTable returned as a HashTable
         
    .PARAMETER InputObject
        The HashTable that you want to extract key(s) from
         
    .PARAMETER Keys
        Names of the key(s) that you want to to extract from the HashTable
         
    .EXAMPLE
        PS C:\> $params = @{NoPrompt = $true; CreateParent = $false}
         
        Get-HashtableKey -InputObject $params -Keys "NoPrompt"
         
        This will return a new HashTable only containing the "NoPrompt" entry.
         
    .NOTES
        Author: Mötz Jensen (@Splaxi)
         
#>

function Get-HashtableKey {
    [CmdletBinding()]
    [OutputType([HashTable])]
    param (
        [parameter(Mandatory = $true, Position = 1)]
        [HashTable] $InputObject,

        [Parameter(Mandatory = $true, Position = 2)]
        [string[]] $Keys
        
    )

    $var = Get-DeepClone $InputObject
    $res = @{}

    foreach ($key in $var.Keys) {
        Write-PSFMessage -Level Verbose -Message "Working on key: $key" -Target $key
        
        if($Keys.Contains($key)) {
            Write-PSFMessage -Level Verbose -Message "Found key: $key" -Target $key
            $null = $res.Add($key, $var.Item($key))
        }
    }

    $res
}