Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing enum values to a function in 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?

like image 410
Paolo Tedesco Avatar asked Jul 20 '10 11:07

Paolo Tedesco


2 Answers

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 :)

like image 144
stej Avatar answered Oct 07 '22 00:10

stej


To avoid the error put the enum value in parenthesis:

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

PS > IsItFriday ([System.DayOfWeek]::Friday)  
yes
like image 43
Shay Levy Avatar answered Oct 06 '22 23:10

Shay Levy