【问题标题】:Powershell REST request wont return server response if 404如果 404,Powershell REST 请求不会返回服务器响应
【发布时间】:2023-12-30 10:25:01
【问题描述】:

我还是 Powershell 的新手,对此一无所知。我正在对 URI 运行 REST GET 请求,我知道该 URI 会从服务器返回 404,因为找不到资源。

我希望能够运行一个条件来检查它是否是 404,如果是这种情况则跳过它以进行进一步处理但是当我将请求分配给一个变量,然后稍后调用它时,它只会给出我请求的内容是什么。我以前从未在其他语言中看到过这样的东西......

我的基本前提如下。我首先获取所有组名称,然后遍历该名称数组,将当前名称包含在新 URL 中,并为该特定组发出额外请求,该组查找始终具有相同名称的 SHIFT。如果该组没有按名称进行的班次,我想跳到下一个组,否则更改该新找到的班次对象的某些属性。

这是我的代码的样子,你可以看到它没有正确运行

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$user = '******'
$pass = ConvertTo-SecureString '*******' -AsPlainText -Force
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $user, $pass
$req  = Invoke-WebRequest -Credential $cred -Uri https://********-np.xmatters.com/api/xm/1/groups
$res  = ConvertFrom-Json $req.Content
$content = $res.data

$base = "https://********-np.xmatters.com/api/xm/1/groups"
$group_name = $content[0].targetName
$path = "$base/$group_name/shifts/MAX-Default Shift"

$shift = Invoke-RestMethod -Credential $cred -Uri $path

Write-Host '-----------------------'
Write-Host $shift
Write-Host '-----------------------'



... RESPONSE BELOW ....



Invoke-RestMethod : The remote server returned an error: (404) Not Found.
At \\MMFILE\********$\MyDocuments\Group Supers PReliminary.ps1:16 char:10
+ $shift = Invoke-RestMethod -Credential $cred -Uri $path
+          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

-----------------------
@{id=***********; group=; name=MAX-Default Shift; description="; start=2018-08-21T04:00:00.000Z; end=2018-08-22T04:00:00.000Z; timezone=America/New_York; recurrence=;
 links=}
-----------------------

PS C:\WINDOWS\system32> 

我想做的是,用简写代码,if $shift.code == 404 ... skip ... else ... run additional query

【问题讨论】:

  • 是的,这是关于Invoke-* web cmdlet 的不幸现实。如果你没有得到内容,而是得到一个不成功的代码,他们会抛出一个错误。
  • 有什么办法吗?
  • 使用-ErrorAction Stop 强制它成为终止错误并使用try/catch 块。

标签: json powershell httprequest response


【解决方案1】:

你需要使用 try ... catch。

$code = ""

try{
    $shift = Invoke-RestMethod -Credential $cred -Uri $path
}
catch{
    $code = $_.Exception.Response.StatusCode.value__
}

if($code -eq "404")
{
    continue
    # Other things
}
else
{

    Write-Host '-----------------------'
    Write-Host $shift
    Write-Host '-----------------------'
}

【讨论】:

    【解决方案2】:

    您可以通过Try..Catch 隐藏错误消息,这样可以让脚本继续:

    Try {
        $Shift = Invoke-RestMethod http://www.google.com/fakeurl -ErrorAction Stop
        #Do other things here if the URL exists..
    } Catch { 
        if ($_.Exception -eq 'The remote server returned an error: (404) Not Found.') {
           #Do other things here that you want to happen if the URL does not exist..
        }
    }
    

    请注意,这将隐藏Invoke-ResetMethod 中的所有终止错误。然后,您可以使用 if 语句来查看异常是否为 404,然后相应地执行进一步的操作。

    【讨论】:

    • 是的,但是就像我之前所说的,我想运行额外的请求,这次是 PUT 请求,但前提是资源存在,所以没有什么可以捕获的,对吧?如果它失败了,就会抓住它。在这种情况下,我的其他内容将进入 TRY 块,如果请求失败,它将中断。
    • 更新了我的答案。这有帮助吗?
    • 是的,如果没有发生异常,您希望发生的事情应该放在Try 中。当出现 404 时,这些行将不会执行,因为一旦发生异常,代码将跳转到 catch