8

The following works fine on my machine which does not use a web proxy.

return Invoke-RestMethod 
   -Uri $server$url 
   -ContentType $contentType 
   -Headers $headers 
   -Method $method 
   -UseDefaultCredentials 

Note: the $server$url is an https address, something like https://somewhere.example.com/api/data

Now I'm trying to get it to work in a corporate environment but I am getting a 401 error.

I think this is because there is a corporate proxy which is defined with a proxy.pac file. I have confirmed I can get to the $server$url URI from Internet Explorer. What do I need to do to get the Invoke-RestMethod command to work using the same settings?

I have tried adding the -proxy parameter

$proxy = [System.Net.WebRequest]::GetSystemWebProxy()
$proxy.Credentials = [System.Net.CredentialCache]::DefaultCredentials

return Invoke-RestMethod 
    -Uri $server$url 
    -ContentType $contentType 
    -Headers $headers 
    -Method $method 
    -UseDefaultCredentials 
    -Proxy $proxy 
    -ProxyUseDefaultCredentials

but the -Proxy parameter is expecting a URI not an IWebProxy object.

shamp00
  • 11,106
  • 4
  • 38
  • 81

2 Answers2

10

The accepted answer got me started. Here's the full version

$headers = @{"X-My-ApiKey"=$apiKey}
$contentType = "application/json"

$proxyUri = [Uri]$null
$proxy = [System.Net.WebRequest]::GetSystemWebProxy()
if ($proxy)
{
    $proxy.Credentials = [System.Net.CredentialCache]::DefaultCredentials
    $proxyUri = $proxy.GetProxy("$server$url")
}

if ("$proxyUri" -ne "$server$url")
{
    Write-Host "Using proxy: $proxyUri"
    return Invoke-RestMethod -Uri $server$url -ContentType $contentType -Headers $headers -Method $method -UseDefaultCredentials -Proxy $proxyUri -ProxyUseDefaultCredentials
}
else
{
    return Invoke-RestMethod -Uri $server$url -ContentType $contentType -Headers $headers -Method $method -UseDefaultCredentials
}
shamp00
  • 11,106
  • 4
  • 38
  • 81
5

Edit: Once incorrect address is provided the command no longer works and returns the address provided instead of the proxy address.. Do not use this: Using the code snippet in this, I am able to retrieve the proxy uri from PowerShell as such:

[System.Net.WebRequest]::DefaultWebProxy.GetProxy([uri]("http://www.google.com"))

Use this instead:

[System.Net.WebRequest]::GetSystemWebProxy().GetProxy("http://www.google.com")

It still returns the provided URI (or throws) when the uri is invalid, but once correct uri is provided is starts working again.

Community
  • 1
  • 1
nohwnd
  • 826
  • 7
  • 13
  • Hmm... in my case the URL is an https address. Then `GetSystemWebProxy().GetProxy()` returns _The ServicePointManager does not support proxies with the https scheme_. – shamp00 Dec 09 '13 at 14:25
  • For some reason after running this command `[System.Net.WebRequest]::GetSystemWebProxy().GetProxy("https://www.google.com")` my original code started working again. – Aaron C Oct 25 '19 at 17:35