如何在 PowerShell 中传递可选参数?

How to pass optional parameters in PowerShell?

这是 Invoke-WebRequest 的包装函数(我删除了很多额外的功能以降低噪音)

function Invoke-SERVERAPI($apiFolder, $adminCredentials, [ValidateSet("GET","POST","PUT","DELETE")]  $HTTPmethod, $contentType, $body, $verbose)
{
    $resp1HTTPCode= 'Not set'
    try
    {
        if ( ($HTTPmethod -eq 'GET') -or ($HTTPmethod -eq 'DELETE'))
        {
            $resp1 = Invoke-WebRequest -Uri $apiFolder -Method $HTTPmethod -Credential $adminCredentials -ContentType $contentType -ErrorAction SilentlyContinue -Verbose:$verbose
        }
        else
        {
            $resp1 = Invoke-WebRequest -Uri $apiFolder -Body $body -Method $HTTPmethod -Credential $adminCredentials -ContentType $contentType -ErrorAction SilentlyContinue -Verbose:$verbose
        }
        $resp1HTTPCode = $resp1.StatusCode

    }
    catch [Exception]
    {
        $resp1HTTPCode = $_.Exception.Response.StatusCode.Value__

    }

    return $resp1HTTPCode
}

我需要在动词 POST 和 PUT 上传递 -body 参数,但不要在 GET 和 DELETE 中传递它。我设法用 IF/ELSE 做到了。

有没有像我在开关参数 -Verbose 中那样在 PowerShell 中实现此目的的更好方法?

你应该看看 about_Functions_Advanced_Parameters 中的 ParameterSetName。它可以帮助您区分不同的参数集。

是的,它涉及形成一个带有参数的哈希表,并使用它来代替或补充参数列表,又名 splatting。在你的情况下,你这样做:

try
{
    $ifbody=@{}
    if ( ($HTTPmethod -eq 'PUT') -or ($HTTPmethod -eq 'POST'))
    {
        $ifbody."Body"=$body
    }
    $resp1 = Invoke-WebRequest -Uri $apiFolder @ifbody -Method $HTTPmethod -Credential $adminCredentials -ContentType $contentType -ErrorAction SilentlyContinue -Verbose:$verbose

    $resp1HTTPCode = $resp1.StatusCode

}

@ifbody 将哈希表还原为 -key=value -key2=value2... cmdlet 或函数的参数序列。