powershellparametersswitch-statement

Powershell "special" switch parameter


I have the powershell function below

Function Test
{
    Param
    (               
        [Parameter()]
        [string]$Text = "default text"
    )

    Write-Host "Text : $($Text)"
}

And I would like to be able to call this function like below :

Test -Text : should display the default text on the host

Test -Text "another text" : should display the provided text on the host

My issue is that the first syntax is not allowed in powershell ..

Any ideas of how I can achieve this goal ? I would like a kind of 'switch' parameter that can take values other than boolean.

Thanks


Solution

  • The problem you're running into is with parameter binding. PowerShell is seeing [string] $Text and expecting a value. You can work around this like so:

    function Test {
        param(
            [switch]
            $Text,
    
            [Parameter(
                DontShow = $true,
                ValueFromRemainingArguments = $true
            )]
            [string]
            $value
        )
    
        if ($Text.IsPresent -and [string]::IsNullOrWhiteSpace($value)) {
            Write-Host 'Text : <default text here>'
        }
        elseif ($Text.IsPresent) {
            Write-Host "Text : $value"
        }
    }
    

    Note: this is a hacky solution and you should just have a default when parameters aren't passed.