Invoke-WebRequest GetSystemWebProxy()

☆樱花仙子☆ 提交于 2019-12-21 00:46:12

问题


Under PowerShell 2.0 I know that you can set the proxy you would like to use without knowing the exact proxy settings by doing something like the following:

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

Now, my question is if I don't know the proxy settings can I use the above and combine it with a PowerShell 3.0 Invoke-WebRequest. Here's what I was hoping to be able to do:

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

$WS.Proxy = $proxy

$login = Invoke-WebRequest https://website.com/login_form.html -SessionVariable WS

However, when I attempt to do this I get an error, (apparently from my company proxy) indicating that my credentials cannot be verified. I'm hoping that this will ultimately work, but perhaps I'm just making a simple mistake.


回答1:


Maybe this can help, I keep it in my profile. It is using the new the $PSDefaultParameterValues preference variable to set the default proxy values for the new web cmdlets. The code detects if I'm in my office environment and set the settings accordingly. This saves me specifying the settings each time I use those commands.

if(Test-Connection myCorpProxy -Count 1 -Quiet)
{
    $global:PSDefaultParameterValues = @{
        'Invoke-RestMethod:Proxy'='http://myCorpProxy:8080'
        'Invoke-WebRequest:Proxy'='http://myCorpProxy:8080'
        '*:ProxyUseDefaultCredentials'=$true
    }
}



回答2:


Use can use this code :

$dest = "http://www.google.fr"
$proxyurl = ([System.Net.WebRequest]::GetSystemWebproxy()).GetProxy($dest)
Invoke-WebRequest $dest -Proxy $proxyurl -ProxyUseDefaultCredentials



回答3:


The actual problem with your code above (even though Shay's is more elegant) is that you're trying to set a property on a variable before it exists. The SessionVariable "$WS" doesn't exist before you call Invoke-WebRequest but you're trying to set the .Proxy property above it.

If it worked at one point, you had probably created an instance of $WS previously and therefore were able to work with the object during testing but on a fresh/dry run when the script was processing top-down, it didn't yet exist.



来源:https://stackoverflow.com/questions/15646079/invoke-webrequest-getsystemwebproxy

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