gpt4 book ai didi

powershell - 从try/catch PowerShell中排除终止错误

转载 作者:行者123 更新时间:2023-12-03 00:06:00 26 4
gpt4 key购买 nike

我很难通过Rest API检查组是否存在。

call Api以检查该组是否存在。我的逻辑:使用“Invoke-RestMethod”来调用API。如果API调用成功(组存在),它将结果存储在“$ reader_response_success”中;如果组不存在,则cmdlet将失败,错误详细信息存储在错误变量“$ reader_response_failure”中。

根据哪个变量具有值,我可以得出group是否存在的结论。但是,我们的框架具有Try / Catch实现。因此,如果该组不存在,则整个脚本将停止执行。

即使API调用失败,我如何确保脚本将继续执行。 (据我所知,如果该组不存在,API调用将失败)。我已将$ errorAction设置为“SilentlyContinue”,但仍会停止脚本执行。

function Test-CoeAzureInstancePowerBI{

param
(
[Parameter (Mandatory = $true, ValueFromPipeline = $true)]
$ServiceConfiguration
)

## TODO: Check if the Reader and Creator Group exists in dwgm
# Checking if ReaderGroup exists
$Group = @{
GroupName = "ITGA_" + $ServiceConfiguration.ReaderGroup
}
$json = $Group | ConvertTo-Json
$reader_response_success = Invoke-RestMethod 'https://api.corpinter.net/dwgm/v1/lookup/' -Headers $ServiceConfiguration.Headers -Method POST -Body $json -ContentType 'application/json' -ErrorVariable $reader_response_failure -ErrorAction SilentlyContinue
# In the above api call,
# $reader_response_success contains data if the group exists
# $reader_response_failure contains data if the group does not exist
if($reader_response_success -eq $null) {$ServiceConfiguration.ReaderGroupExists = $False}

# Checking if ReaderGroup exists
$Group = @{
GroupName = "ITGA_" + $ServiceConfiguration.CreatorGroup
}
$json = $Group | ConvertTo-Json
$creator_response_success = Invoke-RestMethod 'https://api.corpinter.net/dwgm/v1/lookup/' -Headers $ServiceConfiguration.Headers -Method POST -Body $json -ContentType 'application/json' -ErrorVariable $creator_response_failure -ErrorAction SilentlyContinue
# In the above api call,
# $creator_response_success contains data if the group exists
# $creator_response_failure contains data if the group does not exist
if($creator_response_success -eq $null) {$ServiceConfiguration.CreatorGroupExists = $False}


## The instance should be SKIPPED only if both the ReaderGroup and CreatorGroup exist
if($ServiceConfiguration.CreatorGroupExists -eq $true -and $ServiceConfiguration.ReaderGroupExists -eq $true){
return $true
}else{
return $False
}

}

最佳答案

-ErrorAction SilentlyContinue将仅在非终止错误时继续。因此,您可能会遇到终止错误。您可以仅对该特定cmdlet进行错误处理:

try {
$reader_response_success = Invoke-RestMethod 'https://api.corpinter.net/dwgm/v1/lookup/' -Headers $ServiceConfiguration.Headers -Method POST -Body $json -ContentType 'application/json'
} catch {
# Do some error handling here (probably nothing according to your code so far)
}

对第二个 Invoke-RestMethod调用执行相同的操作。

关于powershell - 从try/catch PowerShell中排除终止错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61315812/

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