如果 404,Powershell REST 请求不会 return 服务器响应

Powershell REST request wont return server response if 404

我对 Powershell 还是个新手,还没有找到任何相关信息。我正在 运行 对一个 URI 发出 REST GET 请求,我知道这是一个事实 returns 一个来自服务器的 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> 

我想做的是,在 shorthand 代码中,if $shift.code == 404 ... skip ... else ... run additional query

您可以通过 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,然后相应地执行进一步的操作。

您需要使用 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 '-----------------------'
}