我对Powershell还不熟悉,还没能在上面找到任何东西。我正在运行对URI的REST请求,因为没有找到资源,因此我知道它会从服务器返回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
发布于 2018-11-13 14:49:55
您可以通过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,然后相应地执行进一步的操作。
发布于 2018-11-13 14:59:28
你得试试..。接住。
$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 '-----------------------'
}https://stackoverflow.com/questions/53283382
复制相似问题