Reputation: 165
I have a variable that is a hash table:
PS C:\depot\code\rp4vm> $skey
key value
--- -----
Splitter version 5.2.P1(a.362)
OS version VMkernel na1-pdesx09
I am trying to access the values for the keys but I cannot seem to. No matter how I address them I get nothing:
PS C:\depot\code\rp4vm> $skey."Splitter version"
PS C:\depot\code\rp4vm> $skey["Splitter version"]
I checked to see if it had key and value pairs:
PS C:\depot\code\rp4vm> $skey.key
Splitter version
OS version
PS C:\depot\code\rp4vm> $skey.value
5.2.P1(a.362)
VMkernel na1-pdesx09.americas.global-legal.com
I am running PowerShell 7 and nothing else appears to have changed in the help files on how to handle hash tables. Does anyone have an idea as to how I can capture the information?
Upvotes: 0
Views: 2429
Reputation: 23862
To complement the answer from @Theo, I suspect that is actually concerns a list of KeyValuePair
objects, like:
$skey =
(new-object 'System.Collections.Generic.KeyValuePair[String, String]' 'Splitter version', '5.2.P1(a.362)'),
(new-object 'System.Collections.Generic.KeyValuePair[String, String]' 'OS version', 'VMkernel na1-pdesx09'),
(new-object 'System.Collections.Generic.KeyValuePair[String, String]' 'OS version', 'VMkernel na2-other')
Anyways, the difference between a hash table and a list of [KeyValuePair]
(or [pscustomobject]
) objects is that a list of objects doesn't require unique keys (as shown in the example above). Meaning that the problem could be that converting them to a hash table, might overwrite duplicate keys.
To retrieve the specific key from the list use:
($skey | Where key -eq 'Splitter version').Value
5.2.P1(a.362)
or multiple keys:
($skey | Where key -eq 'OS version').Value
VMkernel na1-pdesx09
VMkernel na2-other
Upvotes: 0
Reputation: 61253
What you have is definitely not a Hashtable. More likely it is an array of objects that have properties key
and value
like this
$skey = [PsCustomObject]@{'key' = 'Splitter version'; 'value' = '5.2.P1(a.362)'},
[PsCustomObject]@{'key' = 'OS version'; 'value' = 'VMkernel na1-pdesx09'}
To demonstrate:
$skey | ForEach-Object {
Write-Host ('{0} = {1}' -f $_.key, $_.value)
}
Should show
Splitter version = 5.2.P1(a.362) OS version = VMkernel na1-pdesx09
You can convert to a Hashtable if you like:
$hash = @{}
$skey | ForEach-Object {
$hash[$_.key] = $_.value
}
Typing this on mobile, so hopefully got the formatting right..
Upvotes: 2