gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 06:55:54 27 4
gpt4 key购买 nike

这是 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com