【发布时间】: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