Skip to content

Instantly share code, notes, and snippets.

@sassdawe
Created October 14, 2023 09:30
Show Gist options
  • Save sassdawe/60ef1666667f742f97cbff17057e2fb3 to your computer and use it in GitHub Desktop.
Save sassdawe/60ef1666667f742f97cbff17057e2fb3 to your computer and use it in GitHub Desktop.
Mandatory user provided parameter in PowerShell
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
}
@sassdawe
Copy link
Author

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:

image

@Jaykul
Copy link

Jaykul commented Oct 18, 2023

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