PowerShell, Web Requests, and Proxies

北慕城南 提交于 2019-11-28 16:12:59

Untested:

$user = $env:username
$webproxy = (get-itemproperty 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet
Settings').ProxyServer
$pwd = Read-Host "Password?" -assecurestring

$proxy = new-object System.Net.WebProxy
$proxy.Address = $webproxy
$account = new-object System.Net.NetworkCredential($user,[Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($pwd)), "")
$proxy.credentials = $account

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

...

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
    $wc
}
Shay Levy
$proxy = New-Object System.Net.WebProxy("http://yourProxy:8080")
$proxy.useDefaultCredentials = $true
$wc = new-object system.net.webclient
$wc.proxy = $proxy
$wc.downloadString($url)

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!

Rene Abrego

Just update the URL with your own proxy address:port. It enables PowerShellGet to go past the proxy using your local credentials. If you don't have credential requirement, just click OK when prompted for your password. I renamed that box to "Close this window". You can also use other package managers like Chocolatey/Nuget through the proxy because of this script.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!