如果失败,调用 WebRequest 为 null

Invoke-WebRequest to null if it fails

我在我的脚本中 运行 这部分代码,但我有一个小问题。

$response = Invoke-WebRequest -Uri "http://169.254.169.254/metadata/instance/compute?api-version=2019-06-01" -Headers @{Metadata = "true"} -TimeoutSec 1 -ErrorAction SilentlyContinue
    if($response.StatusCode -ne 200) {
    write-host "$env:computername is not in the cloud. Let's continuing configurations"
    configuration code
    }else{
     write-host "$env:computername is  in the cloud. Stop the script"
    }

当调用失败时,在我的情况下,99% 的时间它都会输出失败的大红色错误消息,我想摆脱它

然后我尝试使用这些命令抑制 invoke-webrequest 的输出,但是 none 它们起作用了

| Out-Null
> $null
$null =

也尝试过使用 Try & Catch,但也没有成功,因为不知何故我从来没有达到我的最后一个 if 语句

Write-Verbose "Checking if this is an Azure virtual machine"
try {
    $response = Invoke-WebRequest -Uri "http://169.254.169.254/metadata/instance/compute?api-version=2019-06-01" -Headers @{Metadata = "true"} -TimeoutSec 1 -ErrorAction SilentlyContinue
}
catch {
    Write-Verbose "Error $_ checking if we are in Azure"
    return $false
}
if ($null -ne $response -and $response.StatusCode -eq 200) {
    Write-Verbose "Azure check indicates that we are in Azure"
    return $true
}
return $false

if($false -eq 'False')
{
Write-Host "server is in Azure"
}
else{
Write-host "server is not in Azure"
}

接下来我应该尝试什么?我不太擅长 PowerShell,因此甚至可能存在一些语法错误或误解。

我用 Invoke-WebRequest 做了一些测试,并且能够用 try & catch 抑制错误。尝试这样的事情:

Write-Verbose "Checking if this is an Azure virtual machine"
try {
    $response = Invoke-WebRequest -Uri "http://169.254.169.254/metadata/instance/compute?api-version=2019-06-01" -Headers @{Metadata = "true"} -TimeoutSec 1 -ErrorAction Stop

    # Response was successful (200), otherwise script would run in catch at this point
    Write-Verbose "$env:computername is  in the cloud. Stop the script"
} catch {
    # Webrequest failed (not 200)
    Write-Verbose "$env:computername is not in the cloud. Let's continuing configurations"

    # CONFIGURATION CODE
}