Created
October 14, 2023 09:30
-
-
Save sassdawe/60ef1666667f742f97cbff17057e2fb3 to your computer and use it in GitHub Desktop.
Mandatory user provided parameter in PowerShell
This file contains hidden or 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 mandatoryUserBoolParam { | |
param( | |
[Parameter(Mandatory=$true)] | |
[ValidateSet("true","false","1","0","yes","no","y","n")] | |
[string]$param | |
) | |
$boolParam = $false | |
switch ($param.ToLower()) { | |
"true" { $boolParam = $true } | |
"1" { $boolParam = $true } | |
"yes" { $boolParam = $true } | |
"y" { $boolParam = $true } | |
default { $boolParam = $false } | |
} | |
$boolParam | |
} |
class SwitchTransformAttribute : System.Management.Automation.ArgumentTransformationAttribute {
[object] Transform([System.Management.Automation.EngineIntrinsics]$EngineIntrinsics, [object]$Object) {
if ($Object -is [bool]) { return [bool]$object }
if ("$Object".ToLower() -in "yes","true",'$true',"1","y") { return $true }
if ("$Object".ToLower() -in "no","false",'$false',"0","n") { return $false }
# if you wanted to _never_ have a conversion failure, you could just:
# return [bool]$object
# But this way, if they just mash the keyboard, "asdf" won't be treated as $true
return $object
}
}
function Test-Switch {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[SwitchTransform()]
[switch]
$Seriously
)
$Seriously.IsPresent
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I considered using
[switch]
but I needed something mandatory without default values and prone to errors which also looks kind of OK in when not provided: