将枚举值传递给PowerShell中的函数 [英] Passing enum values to a function in PowerShell

查看:105
本文介绍了将枚举值传递给PowerShell中的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数接受一个枚举值作为参数。例如,请考虑以下内容:

I have a function accepting an enum value as parameter. As an example, consider something like:

(PS) > function IsItFriday([System.DayOfWeek] $dayOfWeek) { 
    if($dayOfWeek -eq [System.DayOfWeek]::Friday) {
        "yes"
    } else {
        "no"
    } 
}

现在,如果我这样调用它,一切都很好:

Now, if I invoke it like this, everything is fine:

(PS) > $m = [System.DayOfWeek]::Monday
(PS) > IsItFriday $m
no

但是如果我调用直接传递枚举值的函数,我得到一个相当神秘的错误:

But if I call the function passing directly the enum value, I get a rather cryptic error:

(PS) > IsItFriday [System.DayOfWeek]::Monday
IsItFriday : Cannot convert value "[System.DayOfWeek]::Monday" to type "System.DayOfWeek" 
due to invalid enumeration values. Specify one of the following enumeration values and 
try again. The possible enumeration values are "Sunday, Monday, Tuesday, Wednesday, 
Thursday, Friday, Saturday".
At line:1 char:11
+ IsItFriday  <<<< [System.DayOfWeek]::Monday

用枚举值初始化变量和传递变量有什么区别

What's the difference between initializing a variable with the enum value and passing the enum value directly?

推荐答案

是的,这是一个相当混乱的错误消息。我想您可以举个例子更好地理解:

Yes, that is a rather confusing error message. I think you would understand better with an example:

Get-ChildItem -Path C:\

请注意, C:\ 周围没有引号,因为隐式地转换为字符串,并且两个,当您将该路径作为参数传递给某些被调用方时,没有必要将不包含空格的路径括起来。

Notice there are no quotes around C:\ because, one, it implcitly gets converted to a string, and two, it is not necessary to enclose a path which does not contain spaces when you pass the path as a parameter to some callee.

因此,让我们回到您的函数,并对其稍作更改:

So lets go back to your function, and change it slightly:

function IsItFriday($dayOfWeek) 
{
    $dayOfWeek.GetType()

    if ($dayOfWeek -eq [System.DayOfWeek]::Friday) 
    {
        "yes"
    } 
    else 
    {
        "no"
    }
}

IsItFriday [System.DayOkWeek]::Monday

...并输出:

IsPublic IsSerial Name                                     BaseType                                                                                        
-------- -------- ----                                     --------                                                                                        
True     True     String                                   System.Object                                                                                   
no

看看那里发生了什么? PowerShell认为您传递的是字符串而不是枚举值,因此这就是为什么您得到无法转换值 [System.DayOfWeek] :: Monday 的原因,因为这是文字传入的字符串。

See what happened there? PowerShell thinks you are passing in a string instead of an enumeration value, so that's why you get Cannot convert value "[System.DayOfWeek]::Monday" because that is the literal string that gets passed in.

这篇关于将枚举值传递给PowerShell中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆