Powershell “special” switch parameter

前端 未结 2 758
礼貌的吻别
礼貌的吻别 2020-12-20 03:45

I have the powershell function below

Function Test
{
    Param
    (               
        [Parameter()]
          


        
2条回答
  •  天涯浪人
    2020-12-20 04:12

    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 : '
        }
        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.

提交回复
热议问题