PowerShell

PowerShell: Enumeration with the Enum Statement

The enum statement can be used to declare an enumeration. Microsoft describes this statement as follows:

The enum statement allows you to create a strongly typed set of labels. That enumeration can be used in the code without having to parse or check for spelling errors.

Enumerations are internally represented as integers with a starting value of zero. The first label in the list is assigned the value zero. The remaining labels are assigned with consecutive numbers.

In the definition, labels can be given any integer value. Labels with no value assigned take the next integer value.

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_enum?view=powershell-7.2

Now I would like to give you an example to buid on.

I am going to write some error codes …

The syntax is

enum ErrorCodes {
    Error = 1
    Warning = 2
    Critical = 3
}

Now I call error 1.

'1' -as [ErrorCodes]

Wooh! It returns Error. That’s correct!

For more deep dive in enum simply start discovering the enum attributes.

[Errorcodes].GetType()
[Errorcodes].GetEnumNames()
[Errorcodes].GetEnumValues()
[Errorcodes].GetEnumName(1)

Categories: PowerShell

Tagged as: ,

3 replies »

  1. i understand powershell but in certain way newbie, sound interesting this matter of [errorcodes] would yo mind to give some examples please!

    Like

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.