Passing enum values to a function in PowerShell

后端 未结 4 1889
悲&欢浪女
悲&欢浪女 2021-02-19 20:52

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

(PS) > function IsItFriday([System.DayOfWeek] $dayOfWeek) { 
          


        
相关标签:
4条回答
  • 2021-02-19 21:22

    It's a little bit unexpected - you need to wrap it in parenthesis so that the value is evaluated:

    > IsItFriday ([System.DayOfWeek]::Monday)
    

    also it is possible to pass only strings like this:

    > IsItFriday Monday
    no
    > IsItFriday Friday
    yes
    

    PowerShell will convert it to the enum type. Handy, isn't it :)

    0 讨论(0)
  • 2021-02-19 21:41

    To avoid the error put the enum value in parenthesis:

    PS > IsItFriday ([System.DayOfWeek]::Monday)  
    no
    
    PS > IsItFriday ([System.DayOfWeek]::Friday)  
    yes
    
    0 讨论(0)
  • 2021-02-19 21:43

    Even handier is that strings will get converted to enum values if valid:

    function IsItFriday([System.DayOfWeek] $dayOfWeek) {   
        if($dayOfWeek -eq [System.DayOfWeek]::Friday) {  
            "yes"  
        } else {  
            "no"  
        }   
    }
    
    PS 7> IsItFriday Monday
    no
    PS 8> IsItFriday Friday
    yes
    
    0 讨论(0)
  • 2021-02-19 21:45

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

    Get-ChildItem -Path 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
    

    ...and the output:

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

    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.

    0 讨论(0)
提交回复
热议问题