在PowerShell中使用枚举类型

来源:互联网 发布:国轩高科待遇 知乎 编辑:程序博客网 时间:2024/05/22 15:47

我们都知道PowerShell是基于NET Framework库的,自从PowerShell开始支持Class关键字后,我们也可以在PowerShell使用Enum枚举,我们先给出下面这个完整的小例子。

#requires -Version 5 enum MyFruit {  Apple  Orange  Watermelon}  function Select-Fruit{  param  (    [MyFruit]    [Parameter(Mandatory=$true)]    $Fruit  )    "You like $Fruit"}Select-Fruit


使用方法如下,我们把如上脚本保存为一个ps1脚本,然后直接运行,根据提示输入特定的水果名,得到了正确的结果。 
PS C:\Users\Administrator> C:\Sample\Untitled4.ps1cmdlet Select-Fruit at command pipeline position 1Supply values for the following parameters:Fruit: AppleYou like Apple


简单讲解下之前的小例子,我们用enum关键字声明了一个简单的枚举类型。
enum MyFruit {  Apple  Orange  Watermelon}


然后按照我们平时定义各种常用类型那样,用我们自定义的类型去定义$Fruit变量,将它定义为了一个[MyFruit]类型,所以很简单,这个变量其实就是一个包含了枚举的变量了。
    [MyFruit]    [Parameter(Mandatory=$true)]    $Fruit

我们可以简单修改下脚本,看看是否它是一个枚举:

#requires -Version 5 enum MyFruit {  Apple  Orange  Watermelon}  function Select-Fruit{  param  (    [MyFruit]    [Parameter(Mandatory=$true)]    $Fruit  )    $Type = ($Fruit).GetType() | Select-Object -ExpandProperty BaseType  "The type is $Type"}Select-Fruit

得到结果如下,就是这样!

PS C:\Users\Administrator> C:\XMLSample\Untitled4.ps1cmdlet Select-Fruit at command pipeline position 1Supply values for the following parameters:Fruit: appleThe type is System.Enum


0 0