Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a string parameter sent to PowerShell not really a string?

Tags:

powershell

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.

like image 986
Peter Moberg Avatar asked Aug 19 '10 17:08

Peter Moberg


1 Answers

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).

like image 189
JaredPar Avatar answered Sep 24 '22 19:09

JaredPar