PowerShell不能使用匹配的枚举类型?

jpm*_*c26 7 parameters powershell enums types

我在这里做些蠢事吗?

我指定一个函数将特定的枚举类型作为参数:

PS> add-type -AssemblyName System.ServiceProcess
PS> function test([System.ServiceProcess.ServiceControllerStatus]$x) { Write-host $x $x.gettype() }
Run Code Online (Sandbox Code Playgroud)

该类型绝对是范围,因为我可以访问它的实例(并且我手动导入了程序集):

PS> [System.ServiceProcess.ServiceControllerStatus]::Stopped
Stopped
Run Code Online (Sandbox Code Playgroud)

然后,当我尝试将函数传递给所述枚举的实例时,它会出错:

PS> test [System.ServiceProcess.ServiceControllerStatus]::Stopped
test : Cannot process argument transformation on parameter 'x'. Cannot convert value
"[System.ServiceProcess.ServiceControllerStatus]::Stopped" to type "System.ServiceProcess.ServiceControllerStatus".
Error: "Unable to match the identifier name [System.ServiceProcess.ServiceControllerStatus]::Stopped to a valid
enumerator name.  Specify one of the following enumerator names and try again: Stopped, StartPending, StopPending,
Running, ContinuePending, PausePending, Paused"
At line:1 char:6
+ test [System.ServiceProcess.ServiceControllerStatus]::Stopped
+      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [test], ParameterBindingArgumentTransformationException
    + FullyQualifiedErrorId : ParameterArgumentTransformationError,test
Run Code Online (Sandbox Code Playgroud)

但是强迫一个字符串非常高兴:

PS> test 'Stopped'
Stopped System.ServiceProcess.ServiceControllerStatus
Run Code Online (Sandbox Code Playgroud)

这是怎么回事?

(PowerShell错误消息看起来很混乱.= /)

Jas*_*irk 10

你遇到了关于解析模式的小问题.你可以在论证周围加上parens,它会起作用:

test ([System.ServiceProcess.ServiceControllerStatus]::Stopped)
Run Code Online (Sandbox Code Playgroud)

或者,从字符串到枚举的转换自然发生,因此您可以写:

test Stopped
Run Code Online (Sandbox Code Playgroud)

以下是一些讨论解析模式的好链接:

http://technet.microsoft.com/en-us/library/hh847892.aspx http://rkeithhill.wordpress.com/2007/11/24/effective-powershell-item-10-understanding-powershell-parsing-modes /