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

标签 powershell powershell-3.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 做到了。

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

最佳答案

是的,它涉及形成一个带有参数的哈希表,并使用它来代替或补充参数列表,又名 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 或函数的参数序列。

关于powershell - 如何在 PowerShell 中传递可选参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31429505/

相关文章:

powershell - Powershell:简单的Foreach添加

function - 如何允许使用-erroraction调用函数

regex - 提取并重命名为数字 ID

git - PowerShell Git diff 从参数传递到参数

powershell - PSSessionStateBroken 在计划任务中带有 start-job -credential

powershell - 在 Windows10 上使用 NSIS 启用应用侧载

powershell - 使用 powershell 在文件末尾添加多行

powershell - 每个对象内的每个对象

bash - 在powershell中使用mkdir创建多个子目录

Powershell 导入-CSV : either reorder columns with no headers or export-CSV with no header