PowerShell枚举值代表所有

时间:2013-05-02 16:02:31

标签: c# powershell powershell-v2.0

鉴于我当前的enum

Add-Type -TypeDefinition @"
   [System.Flags] 
   public enum FlagsEnum {
      None = 0,
      SummaryInfo = 1,
      ReportOptions = 2,
      ParameterFields = 4
   }
"@

有没有办法创建一个将所有位设置为1的条目?此语法会导致错误:

Add-Type -TypeDefinition @"
   [System.Flags] 
   public enum FlagsEnum {
      None = 0,
      SummaryInfo = 1,
      ReportOptions = 2,
      ParameterFields = 4,
      All = (SummaryInfo -bor ReportOptions -bor ParameterFields)
   }
"@

**编辑**

更改声明:

Add-Type -TypeDefinition @"
   [System.Flags] 
   public enum FlagsEnum {
      None = 0,
      SummaryInfo = 1,
      ReportOptions = 2,
      ParameterFields = 4,
      All = (SummaryInfo | ReportOptions | ParameterFields)
   }
"@

代码:

$flags = [FlagsEnum]::All

if ( $flags -band [FlagsEnum]::SummaryInfo ) { write-host "add SummaryInfo" } 
if ( $flags -band [FlagsEnum]::ReportOptions ) { write-host "add ReportOptions" } 
if ( $flags -band [FlagsEnum]::ParameterFields ) { write-host "add ParameterFields" } 

结果:

Add-Type : Cannot add type. The type name 'FlagsEnum' already exists.
At C:\Documents and Settings\xxx\My Documents\WindowsPowerShell\Scripts\enums.ps1:3 char:9
+ Add-Type <<<<  -TypeDefinition @"
    + CategoryInfo          : InvalidOperation: (FlagsEnum:String) [Add-Type], Exception
    + FullyQualifiedErrorId : TYPE_ALREADY_EXISTS,Microsoft.PowerShell.Commands.AddTypeCommand

2 个答案:

答案 0 :(得分:4)

试试这个:

Add-Type -TypeDefinition @"
  [System.Flags] 
  public enum FlagsEnum {
    None = 0,
    SummaryInfo = 1,
    ReportOptions = 2,
    ParameterFields = 4,
    All = (SummaryInfo | ReportOptions | ParameterFields)
  }
"@

请记住,在这里的doc中,你并没有真正编写PowerShell,而是在编写C#。

根据原始问题的提问者的评论

编辑后代

显示的实际错误表明该类型已存在。这是因为早期版本的代码已在同一PowerShell会话中运行。 PowerShell的一个不幸的限制是你不能添加一个类型,调整它然后重新添加它(这使得开发定义自己类型的脚本变得痛苦)。

答案 1 :(得分:3)

您正在定义C#枚举,因此请使用C#运算符,例如:

 All = SummaryInfo | ReportOptions | ParameterFields