Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 930
Riana Avatar asked Mar 03 '23 04:03

Riana


1 Answers

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.

like image 68
Maximilian Burszley Avatar answered Mar 07 '23 02:03

Maximilian Burszley