Home > Enterprise >  Retrieving data from map returns null
Retrieving data from map returns null

Time:02-19

I'm trying to retrieve info from a map.

The map looks like this:

$VideoIDs:

[Object[7]]
[0]: @{Key=Load_Sheet; Value =}
[1]: @{Key=Load_Folded; Value =FormLoad}
[2]: @{Key=Load_Media; Value =}
...

(where the empty Values really should be that way)

This info is obtained similar to get info from xml, except for the same keys, I'm getting VideoID instead of AlarmID.

I'm trying to retrieve the info for Load_Folded, and this is returning null, even though I can see it should be FormLoad.

$tmp = "Load_Folded"
$videoIdentifierString = $VideoIDs.$tmp  #gives null...same as if I do $VideoIDs[$tmp]   or $VideoIDs[$($tmp)]  or   $VideoIDs["$($tmp)"]

Any idea how to get this info out of the map? I can't iterate over this map, and just need to obtain the value given the key.

This is with powershell 5.1 and VS Code.

CodePudding user response:

This goes about filtering objects in an array in PowerShell, a good documentation to have a good concept on this is probably Where-Object even though there are many ways of accomplishing this some more efficient than others.

Given the array of pscustomobject you currently have:

$result = @(
    [pscustomobject]@{ Key = 'Load_Sheet';  Value = '' }
    [pscustomobject]@{ Key = 'Load_Folded'; Value = 'FormLoad' }
    [pscustomobject]@{ Key = 'Load_Media';  Value = '' }
)
  • Using Where-Object:
($result | Where-Object Key -EQ 'Load_Folded').Value
  • Using .Where(..):
$result.Where({ $_.Key -eq 'Load_Folded' }).Value
  • Using foreach and an if condition:
foreach($item in $result) {
    if($item.Key -eq 'Load_Folded') {
        $item.Value
    }
}
  • Related