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

时间:2015-07-15 11:45:37

标签: powershell powershell-v3.0

这是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做到了。

有没有更好的方法在PowerShell中实现这一点,就像我在switch参数-Verbose中所做的那样?

1 个答案:

答案 0 :(得分:4)

是的,它涉及使用参数形成哈希表并使用它代替或添加参数列表,即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或函数。