Reputation: 2018
I am struggling with PowerShell. I would like to access a data structure that is itemized by Enums. When executing this demo code below, I get a error message I do not understand:
Index operation failed; the array index evaluated to null.
Any help would be appreciated,
Thanks
Powershell code:
Enum X {
X1
X2
}
Enum Y {
Y1
Y2
}
$map = @{
[X]::X1=@{
[Y]::Y1="Hello World"
};
[X]::X2=@{
[Y]::Y1="Hello World"
}
};
function getElementFromMap([X] $x, [Y] $y) {
Write-Host $map[$x][$y]
}
getElementFromMap([X]::X1, [Y]::Y1);
Upvotes: 2
Views: 430
Reputation: 17055
They way you are calling the function is not correct. In PowerShell, arguments for commands (or function calls) are seperated by whitespace, not commas. A comma will make PowerShell interpret both values as an array.
Do this instead:
getElementFromMap ([X]::X1) ([Y]::Y1)
The brackets are there so PowerShell evalues the expressions, and does not treat them as strings.
The following would also be possible, because the values would be interpreted as strings and automatically converted in the function, because you specified the parameter types in the function definition ([X]$x, [Y]$y
):
getElementFromMap X1 Y1
# or
getElementFromMap "X1" "Y1"
Look here to learn more about the two parsing modes of PowerShell (expression mode and argument mode).
Upvotes: 1