Search code examples
powershellbooleanvalidateset

PowerShell ValidateSet on Boolean Parameter


I am attempting to use ValidateSet with a boolean parameter however I cannot get it to function as expect.

An example to replicate the issue:

function Set-Boolean
{
    [CmdletBinding()]
    [OutputType([Bool])]
    Param
    (
        [Parameter(Mandatory=$true, Position=0)]
        [ValidateNotNullOrEmpty()]
        [ValidateSet($false,$true)]
        [Bool] $Bool
    )

    Process
    {
        $Bool
    }
}

At run time PowerShell expands the $true and $false variables upon tab completion to True and False respectively however this then cause the parameter validation to fail as only $true, $false, 1 and 0 are valid boolean types.

I tried changing ValidateSet to [ValidateSet('$false','$true')] and the tab completion works as expected however the parameter validation still fails as the parameter is expecting the strings '$false' and '$true'.

I could change ValidateSet to [ValidateSet([bool]0,[bool]1)] and have it function as I expect but I find 0 and 1 a poorer user experience over $true and $false for completion of a boolean parameter.

The expected output of the function should be True when $true is chosen and False when $false is chosen.

I have implemented a workaround in my code but I want to know how I can use ValidateSet with a boolean parameter, if it is possible, to enable the use of tab completion for the user.


Solution

  • You can use ValidateSet for autocompletion without specifying the input variable type. Though, you cannot use 0 and 1 as input in this case:

    function Set-Boolean
    {
        [CmdletBinding()]
        [OutputType([Bool])]
        Param
        (
            [Parameter(Mandatory=$true, Position=0)]
            [ValidateNotNullOrEmpty()]
            [ValidateSet($false,$true)]
            $Bool
        )
    
        Process
        {
            [System.Convert]::ToBoolean($Bool)
        }
    }