Search code examples
powershellinvoke-webrequest

Invoke-WebRequest to null if it fails


I'm running this part of the code in my script but I have small issue.

$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"
    }

When the invoke fails which in my cases does 99% of the time it outputs the fail as big red error message which I would want to get rid of enter image description here

Then I tried to suppress to output of the invoke-webrequest using these command but none of them worked

| Out-Null
> $null
$null =

Tried also to play with Try & Catch but did not manage to it work either because I somehow never got to my last if statement

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"
}

What should I try next? I'm not super good at PowerShell so there might even just be some errors in syntax or misunderstandings.


Solution

  • I've done some tests with Invoke-WebRequest and was able to suppres the error with try & catch. Try something like that:

    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
    }