Using enumerations to convert values

Considering that enumerations are lists of names, each assigned a numeric value. A pair of enumerations to convert between two lists of names, linked only by a common value.

The following example defines two enumerations. The first is a list of values the end user will see, the second holds the internal name required by the code. This simulates, in part, the type of aliasing performed by the wmic command:

enum AliasName {
OS
Process
}

enum ClassName {
Win32_OperatingSystem
Win32_Process
}

A function might use the AliasName enumeration, as shown here:

function Get-CimAliasInstance {
[CmdletBinding()]
param (
[Parameter(Mandatory, Position = 1)]
[AliasName]$AliasName
)

Get-CimInstance -ClassName ([ClassName]$AliasName)
}

The command may now be used with the OS argument for the AliasName parameter. This will be converted to Win32_OperatingSystem by way of the enumeration. Get-CimInstance handles converting that value into a string.

A hashtable is a possible alternative way of providing the same lookup mechanism. Using an enumeration would potentially have an advantage if the enumerations used the Flags attribute, or if one of the enumerations was already present.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.33.178