Accessing .Net KeyValuePairs by Key from Powershell Core/7

60 views Asked by At

What is the best way to access KeyValuePairs from .Net classes in Powershell (core/7)? I have found that the classes I'm trying to use will not let me access the value using the key name in the indexer.

My current theory is that its due to the underlying .net classes making use of Extension methods which Powershell cannot resolve (but I could be on the wrong path with that...).

Here is an example object:

$HTTPMsg = [System.Net.Http.HttpRequestMessage]::new()
$HTTPMsg.Headers.Add("WWW-Authenticate", "Basic realm=C:\xxx")
$HTTPMsg.Headers.Add("Date", "Wed, 02 Mar 2022 09:41:36 GMT")


$HTTPMsg.Headers

***Output:
Key              Value
---              -----
WWW-Authenticate {Basic realm=C:\xxx}
Date             {Wed, 02 Mar 2022 09:41:36 GMT}

Ideally, I would have liked to be able to access the Date value with:

$MyDate = $HTTPMsg.Headers["Date"]

But this returns $null.

So far the best way I've found is as follows, but this looks way harder than it should be:

$MyDate = $HTTPMsg.Headers.Value[$HTTPMsg.Headers.Key.IndexOf("Date")]

What am I missing?

Thanks in advance!

2

There are 2 answers

0
Darin On

Give this a try.

function Get-HttpHeadersKeyValue {
    param (        
        [Parameter(Mandatory = $true, Position = 0)]
        [System.Net.Http.Headers.HttpHeaders]$HttpHeaders,
        [Parameter(Mandatory = $true, Position = 1)]
        [string]$Key
    )
    $Return = $null
    foreach ($HTTPHeader in $HttpHeaders) {
        if ($HttpHeader.Key -eq $Key) {
            $Return = [string]$HttpHeader.Value
        }
    }    
    return $Return
}

$HTTPMsg = [System.Net.Http.HttpRequestMessage]::new()
$HTTPMsg.Headers.Add("WWW-Authenticate", "Basic realm=C:\xxx")
$HTTPMsg.Headers.Add("Date", "Wed, 02 Mar 2022 09:41:36 GMT")

$DateString = Get-HttpHeadersKeyValue $HTTPMsg.Headers 'Date'
$DateString
$DateTime = [DateTime]::ParseExact($DateString, 'R', $null)
$DateTime

Output:

Wed, 02 Mar 2022 09:41:36 GMT

Wednesday, March 2, 2022 9:41:36 AM
0
PeteC On

@Jeroen Mostert answered in the comments:

$HTTPMsg.Headers.GetValues("Date")