PowerShell, Web Requests, and Proxies


When making a simple web request is there a way to tell the PowerShell environment to just use your Internet Explorer's proxy settings?

My proxy settings are controlled by a network policy(or script) and I don't want to have to modify ps scripts later on if I don't have to.

UPDATE: Great info from the participants. The final script template that I'll use for this will look something like the following:

$proxyAddr = (get-itemproperty 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings').ProxyServer
$proxy = new-object System.Net.WebProxy
$proxy.Address = $proxyAddr
$proxy.useDefaultCredentials = $true

$url = "http://stackoverflow.com"
$wc = new-object system.net.WebClient
$wc.proxy = $proxy
$webpage = $wc.DownloadData($url)
$str = [System.Text.Encoding]::ASCII.GetString($webpage)
Write-Host $str
By : BuddyJoe


This is much later than the original question, but still a relevant answer for later versions of PowerShell. Starting in v3, we have two items that can address this:

Invoke-WebRequest - which replaces using system.net.webclient for nearly every scenario

$PSDefaultParameterValues - which can store details for parameters

How to use them together to solve the original problem of proxy settings controlled by a network policy(or script) and not having to modify ps scripts later on?

Invoke-WebRequest comes with -Proxy and -ProxyUseDefaultCredentials parameters.

We store our answers to these parameters in $PSDefaultParameterValues, like so: $PSDefaultParameterValues.Add('Invoke-WebRequest:Proxy','http://###.###.###.###:80') $PSDefaultParameterValues.Add('Invoke-WebRequest:ProxyUseDefaultCredentials',$true)

You can replace 'http://###.###.###.###:80' with $proxyAddr as you will. What scope you choose to store this in, is your choice. I put them into my $profile, so I never have to set these items in my scripts again.

Hope this helps someone!

By : Bewc

$proxy = New-Object System.Net.WebProxy("http://yourProxy:8080")
$proxy.useDefaultCredentials = $true
$wc = new-object system.net.webclient
$wc.proxy = $proxy
By : Shay Levy

Somewhat better is the following, which handles auto-detected proxies as well:

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

$wc = new-object system.net.WebClient
$wc.proxy = $proxy
$webpage = $wc.DownloadData($url)

(edit) Further to the above, this definition appears to work fine for me, too:

function Get-Webclient {
    $wc = New-Object Net.WebClient
    $wc.UseDefaultCredentials = $true
    $wc.Proxy.Credentials = $wc.Credentials

This video can help you solving your question :)
By: admin