Reputation: 26262
Given my current enum
:
Add-Type -TypeDefinition @"
[System.Flags]
public enum FlagsEnum {
None = 0,
SummaryInfo = 1,
ReportOptions = 2,
ParameterFields = 4
}
"@
Is there a way to create an entry that sets all bits to 1? This syntax causes errors:
Add-Type -TypeDefinition @"
[System.Flags]
public enum FlagsEnum {
None = 0,
SummaryInfo = 1,
ReportOptions = 2,
ParameterFields = 4,
All = (SummaryInfo -bor ReportOptions -bor ParameterFields)
}
"@
** edit **
Changed the declaration:
Add-Type -TypeDefinition @"
[System.Flags]
public enum FlagsEnum {
None = 0,
SummaryInfo = 1,
ReportOptions = 2,
ParameterFields = 4,
All = (SummaryInfo | ReportOptions | ParameterFields)
}
"@
The code:
$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" }
results:
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
Upvotes: 1
Views: 1596
Reputation: 4002
Try this:
Add-Type -TypeDefinition @"
[System.Flags]
public enum FlagsEnum {
None = 0,
SummaryInfo = 1,
ReportOptions = 2,
ParameterFields = 4,
All = (SummaryInfo | ReportOptions | ParameterFields)
}
"@
Remember that inside that here doc, you're not really writing PowerShell, you're writing C#.
Edit for posterity based on comments from the asker of the original question
The actual error that was being shown stated that the type already existed. This is because an earlier version of the code had been run in the same PowerShell session. An unfortunate limitation of PowerShell is that you can't add a type, tweak it and then re-add it (which makes developing scripts that define their own types painful).
Upvotes: 4
Reputation: 201652
You're defining a C# enum so use C# operators e.g.:
All = SummaryInfo | ReportOptions | ParameterFields
Upvotes: 3