Tuesday, December 29, 2020

PowerShell: Passing Enumeration Values as Function Parameters

In a previous post PowerShell enumerations were introduced  (see PowerShell: Enumerations). One topic related to enumerations merits additional discussion, namely passing enumeration values to functions. In brief, when passing enumeration values to a function, the enumeration values must be surrounded by parentheses. In the example below line 20 (enumeration value wrapped in parentheses) succeeds when invoked while line 21 ((enumeration value not wrapped in parentheses) generates an exception:


The example of passing enumerations as function parameters in its entirety is as follows where line 20 passes an enumeration value bracketed by parentheses and line 21 passes an enumeration value sans parentheses: 


Invoking line 20 (the enumeration passed with parentheses) displays the following output:

Log Level: Info (2)

Invoking line 21 (the enumeration passed without parentheses) generates an exception which is handled at line 25 (see code above). The first line of text displayed by line 27 is:

System.Management.Automation.ParameterBindingArgumentTransformationException: Cannot process argument transformation on parameter 'logLevel'. Cannot convert value "[LogLevel]::Info" 
to type "LogLevel". Error: "Unable to match the identifier name [LogLevel]::Info to a valid enumerator name. Specify one of the following enumerator names and try again:
Error, Warn, Info"

The error shown by line 28 is follows:


The correct way to pass enumeration values to functions in PowerShell should be clear: parentheses, parentheses, parentheses!

Appendix A: Code from Post

Set-StrictMode -Version 3.0

enum LogLevel {
    Error
    Warn
    Info
}

function Test-PassngEnumAsParameter {
    param
    (
        [Parameter(Mandatory=$true)]
        [LogLevel] $logLevel
    )

    Write-Host "Log Level: $logLevel ($([int]$logLevel))"
}

try {
    Test-PassngEnumAsParameter ([LogLevel]::Info)
    Test-PassngEnumAsParameter [LogLevel]::Info
    Write-Host 'Success'
}

catch {
    $errorRecord = $_    
    Write-Host $errorRecord.Exception
    Write-Host $errorRecord[0].InvocationInfo.PositionMessage
    Write-Host 'Error'
}







No comments :

Post a Comment