Last active
April 22, 2024 08:05
-
-
Save JohnLBevan/f304a3eff2a9001d04f5adc04a99874f to your computer and use it in GitHub Desktop.
Ensures values match the case given in validateset by correcting to match instead of throwing exceptions. Trick thanks to MKlement: https://stackoverflow.com/a/42699260/361842
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Function Convert-StringToValidateSetParameterCase { | |
Param ( | |
[Parameter(Mandatory)] | |
[System.Management.Automation.InvocationInfo]$InvocationInfo | |
, | |
[Parameter(Mandatory)] | |
[string]$ParameterName | |
, | |
[Parameter(Mandatory)] | |
[AllowEmptyString()] | |
[AllowNull()] | |
[string]$ParameterValue | |
) | |
if ($ParameterValue) { | |
( | |
$InvocationInfo.MyCommand.Parameters[$ParameterName].Attributes | | |
Where-Object { $_ -is [ValidateSet] } | |
).ValidValues | Where-Object{$_ -eq $ParameterValue}; | |
} else { | |
$ParameterValue | |
} | |
} | |
# Example | |
Function Test-CorrectingParameterCase { | |
Param ( | |
[Parameter(Mandatory)] | |
[ValidateSet('One', 'Two', 'Three', IgnoreCase = $true)] | |
[string]$Demo | |
) | |
Convert-StringToValidateSetParameterCase -InvocationInfo $MyInvocation -ParameterName 'Demo' -ParameterValue $Demo | |
} | |
Test-CorrectingParameterCase two | |
# Outputs: Two |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment