Advanced Windows PowerShell Scripting Video Training

Advanced Windows PowerShell Scripting Video Training
Advanced Windows PowerShell Scripting Video Training

Monday, March 7, 2016

Find the index of an Item in an Enumeration

Well, I’m back in the warmth of Phoenix.  We had a lot of great questions from our PowerShell class in Toronto last week.  While we were discussion .NET, a question popped up about finding the index number of a value of an enumeration.  Sure, no problem.




Function Get-EnumIndex
{
Param (
    [parameter(Mandatory=$true)]
    $Enum,
   
    [parameter(Mandatory=$true)]
    [String]
    $Value
)

[enum]::GetValues($Enum)|
        foreach { [PSCustomObject]@{ValueName = $_; IntValue = [int]$_  }   } |
        Where ValueName -eq $Value
<#
.SYNOPSIS
Searches and enumeration for the index number of the provided value.

.DESCRIPTION
Searches and enumeration for the index number of the provided value.

.PARAMETER Enum
The enumeration to search.

.PARAMETER Value
The value you are looking for.

.Example
Enum = [Security.Principal.WindowsBuiltInRole]
Get-EnumIndex -Enum $Enum -Value "Administrator"

    ValueName IntValue
    --------- --------
Administrator      544

Returnes the index value of "Administrator from the
enumeration of [Security.Principal.WindowsBuiltInRole]

.Example
 Enum Course {
    North
    NorthEast
    East
    SouthEast
    South
    SouthWest
    West
    NorthWest

}
$Enum = [Course]
Get-EnumIndex -Enum $Enum -Value "West"


ValueName IntValue
--------- --------
     West        6

Uses PowerShell V5 to create an enumeration for Get-EnumIndex
to evaluate.
#>

}


No comments: