0

I am using below code to check the url connectivity

$uri = 'https://blue-vrrp.company_name.com'
try
    {
        $response = Invoke-WebRequest -Uri $uri -UseBasicParsing -TimeoutSec 10 -ErrorAction Stop
        # This will only execute if the Invoke-WebRequest is successful.
        $StatusCode = $Response.StatusCode
        $StatusDescription = $Response.StatusDescription
    }
    catch
    {
        $StatusCode = $_.Exception.Response.StatusCode.value__
        $StatusDescription = $_.Exception.Response.StatusDescription.value__
    }

It gives status code 407 sometimes and sometimes blank. Getting different responses every time as below without try/catch block.

  1. "The underlying connection was closed: An unexpected error occurred on a send."
  2. "The remote server returned an error: (407) Proxy Authentication Required."
  3. Invoke-WebRequest :Access Denied (authentication_failed) Details:Your credentials could not be authenticated: "Credentials are missing.". You will not be permitted access until your credentials can be verified.

Please let me know if it's an issue with WebRequest module or it's an issue with URL it self.

Thanks.

  • 3
    Can you try adding switch `-UseDefaultCredentials` and parameter `-Method Head` ? – Theo Jun 24 '20 at 12:25
  • None of these are issues with the PowerShell module. Whatever resource you're trying to access might require credentials. If you as a use have access and there's no login prompt, use the `-UseDefaultCredentials` switch. If you have to login, add this switch instead `-Credential (Get-Credential)`. More info : https://learn.microsoft.com/en-us/dotnet/api/system.net.webclient.usedefaultcredentials?redirectedfrom=MSDN&view=netcore-3.1#remarks – FoxDeploy Jun 24 '20 at 13:26
  • Collect rather `$_.Exception.Status` as _StatusCode_ and `$_.Exception.Message` or `$_.Exception.InnerException.Message` as _StatusDescription_ because `$_.Exception.Response` could be `$null` inside the `catch` block. – JosefZ Jun 24 '20 at 15:14
  • Does `Invoke-WebRequest` uses proxy by default to hit any URL? – Prashant Shete Jul 03 '20 at 07:05

0 Answers0