I am currently using anonymous functions in Powershell and I noticed there is a weird casting problem when going from System.ValueType to System.Object.
Take the following example:
$f = {
param($InputArray)
Write-Host "`$Arr Type During Call:" ($InputArray.GetType().FullName)
Write-Host "`$Arr Contents During Call:" $InputArray
}
[object[]]$Arr = [object[]]@($true, $false)
Write-Host "`$Arr Type Before Call:" ($Arr.GetType().FullName)
Write-Host "`$Arr Contents Before Call:" $Arr "`n"
$f.Invoke($Arr)
The following example will output the following:
$Arr Type Before Call: System.Object[]
$Arr Contents Before Call: True False$Arr Type During Call: System.Boolean
$Arr Contents During Call: True
It looks like Powershell casted my variable $Arr
into the type System.Boolean
. If I force the parameter to be of type object[]
, a new problem is introduced:
$f = {
param([object[]]$InputArray)
Write-Host "`$Arr Type During Call:" ($InputArray.GetType().FullName)
Write-Host "`$Arr Contents During Call:" $InputArray
}
[object[]]$Arr = [object[]]@($true, $false)
Write-Host "`$Arr Type Before Call:" ($Arr.GetType().FullName)
Write-Host "`$Arr Contents Before Call:" $Arr "`n"
$f.Invoke($Arr)
The new change produces the following output:
$Arr Type Before Call: System.Object[]
$Arr Contents Before Call: True False$Arr Type During Call: System.Object[]
$Arr Contents During Call: True
Powershell is only providing the anonymous function one element of my array. What is going on here?
- Why is Powershell casting to a
boolean
when I clearly am giving it anobject
array? - Even when I force the input parameter's type of the anonymous function, why does Powershell not provide the entire array?