I am bit confused of the behaviour of the script below:
Test.ps1:
param(
[array]$Value = $(throw "Give me a value")
)
Write-Host $Value
$Value | Get-Member -MemberType Method
$Value.ToUpper()
Running the script:
PS C:\Temp> .\weird.ps1 test
TypeName: System.String
Name MemberType Definition
—- ———- ———-
…
ToUpper Method string ToUpper(), string ToUpper(System.Globalization.CultureInfo culture)
…
Method invocation failed because [System.Object[]] doesn’t contain a method named ‘ToUpper’.
At C:\Temp\weird.ps1:6 char:15
+ $Value.ToUpper <<<< ()
+ CategoryInfo : InvalidOperation: (ToUpper:String) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
Why do I get a MethodNotFound exception? Get-Member clearly says it is a string.
What's happening here is that the variable $value
is typed to Object[]
in the script. The call to Get-Member
works because you are piping the value into the function. Hence instead of seeing the array it sees the values in the array which are indeed typed to String
. This can be viewed by using the following Get-Member
call without piping
Get-Member -MemberType Method -InputObject $value
This is also why ToUpper correctly fails (it's an array not a String
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With