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

标签 powershell types parameters enums

我在这里做一些愚蠢的事情吗?

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

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

该类型绝对在范围内,因为我可以访问它的实例(并且我手动导入了程序集):
PS> [System.ServiceProcess.ServiceControllerStatus]::Stopped
Stopped

然后,当我尝试将上述枚举的实例传递给该函数时,它会出错:
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

但是,强制使用字符串很高兴:
PS> test 'Stopped'
Stopped System.ServiceProcess.ServiceControllerStatus

这是怎么回事?

最佳答案

您在解析模式方面遇到了一个小问题。您可以在参数周围放置括号,它会起作用:

test ([System.ServiceProcess.ServiceControllerStatus]::Stopped)
或者,从字符串到枚举的转换自然发生,因此您可以编写:
test Stopped
这里有几个很好的链接,讨论解析模式:
  • About Parsing
  • Effective PowerShell Item 10: Understanding PowerShell Parsing Modes
  • 关于PowerShell 不能使用匹配的枚举类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25732814/

    相关文章:

    regex - REGEX从.1-5抓取一个数字

    javascript - 如何按共同特征组织数据?

    javascript - 如何在参数之类的函数中使用函数调用者变量?

    ruby-on-rails - Rails 5.1 minitest 展平 params 中的数组数组

    powershell - 在 PowerShell 中创建新的 System.Collections.Generic.Dictionary 对象失败

    powershell - 列出域内远程计算机的硬盘信息

    sharepoint - 无法使用Sharepoint PowerShell更新列表字段属性

    c++ - 如何在 C++ 中推断函数参数类型?

    list - 解释为什么不同类型的列表是一个有效的 Haskell 表达式

    url - 我需要 iHotelier 系统的参数列表,可以在 url 中传递