Skip to content

Instantly share code, notes, and snippets.

@JohnLBevan
Last active April 22, 2024 08:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JohnLBevan/f304a3eff2a9001d04f5adc04a99874f to your computer and use it in GitHub Desktop.
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
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