发送到PowerShell的字符串参数不是真正的字符串吗?

Pet*_*erg 5 powershell

我对下面脚本的行为感到有点困惑:

Test.ps1:

param(
    [array]$Value = $(throw "Give me a value")
)

Write-Host $Value 
$Value | Get-Member -MemberType Method
$Value.ToUpper()
Run Code Online (Sandbox Code Playgroud)

运行脚本:

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
Run Code Online (Sandbox Code Playgroud)

为什么我得到一个MethodNotFound异常?Get-Member清楚地说它是一个字符串.

Jar*_*Par 5

这里发生的是在脚本中$value键入变量Object[].调用是Get-Member有效的,因为您将值传递给函数.因此,它不是看到数组,而是看到数组中确实键入的值String.这可以通过使用以下Get-Member调用来查看,而无需管道

Get-Member -MemberType Method -InputObject $value
Run Code Online (Sandbox Code Playgroud)

这也是ToUpper正确失败的原因(它不是一个数组String).