PowerShell 5.1 introduced classes (which were partially reviewed in post PowerShell: Classes Static Constructors, Static Methods, and Static Properties) and enumerations. Microsoft's documentation on enumeration describes them as (see About Enum):
An example of a too commonly defined (regardless of language) enumeration is as follows where the enumeration values are Error, Warn, and Info:
When displayed, by default, an enumeration value is displayed as text but each enumeration value is associated with a numeric value (Error = 0, Warn = 1, and Info = 2). The following script snippet demonstrates this:
The output from the above snippet is as follows:
Enumerations can be compared using standard numeric operators such as -eq, -ne, -le, -lt, -ge, and -gt. An example of comparing two enumerations is line 98 below which limits the logs displayed to being Error only or Error/Warning or Error/Warn/Info (a.k.a. the current log level):
The enumerations numeric values can also be used as array index. Consider the following enumeration also used the SimpleLogEntry class:
The code which converts a log entry to a line of text is as follows where each property of the SimpleLogEntry class is separated by a delimiter (a tab character) when converted to a string using the ToString method:
- Create an instance of SimpleLogEntry using the constructor that takes a LogLevel enumeration and a message parameter (lines 77-78)
- Get the string representation of the SimpleLogEntry using the ToString method (line line 79)
- Creates a second instance of SimpleLogEntry using the constructor that takes a string (a line of text created from ToString) as a parameter (lines 80-81)
- Get the string representation of the second SimpleLogEntry instance from ToString (line 82)
- Compare the string representation of both SimpleLogEntry instances and if they are equal the test was successful (lines 84-86)
- If the two instance of SimpleLogEntry do not match, throw an exception (line 88)
No comments :
Post a Comment