Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/cocoa/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Powershell 调用WebRequest GetSystemWebProxy()_Powershell_Powershell 3.0 - Fatal编程技术网

Powershell 调用WebRequest GetSystemWebProxy()

Powershell 调用WebRequest GetSystemWebProxy(),powershell,powershell-3.0,Powershell,Powershell 3.0,在PowerShell 2.0下,我知道您可以通过执行以下操作来设置要使用的代理,而不必知道确切的代理设置: $proxy = [System.Net.WebRequest]::GetSystemWebproxy() $proxy.Credentials = [System.Net.CredentialCache]::DefaultCredentials 现在,我的问题是,如果我不知道代理设置,我可以使用上面的设置,并将其与PowerShell 3.0Invoke WebRequest结合使用

在PowerShell 2.0下,我知道您可以通过执行以下操作来设置要使用的代理,而不必知道确切的代理设置:

$proxy = [System.Net.WebRequest]::GetSystemWebproxy()
$proxy.Credentials = [System.Net.CredentialCache]::DefaultCredentials
现在,我的问题是,如果我不知道代理设置,我可以使用上面的设置,并将其与PowerShell 3.0
Invoke WebRequest
结合使用吗。以下是我希望能够做到的:

$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

然而,当我尝试这样做时,我得到一个错误(显然是来自我的公司代理),表明我的凭据无法验证。我希望这最终会奏效,但也许我只是犯了一个简单的错误。

也许这会有所帮助,我会把它保存在我的个人资料中。它使用新的
$PSDefaultParameterValues
首选项变量为新的web cmdlet设置默认代理值。代码检测我是否在办公室环境中,并相应地设置设置。这样,我就可以在每次使用这些命令时指定设置

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

上面代码的实际问题(尽管Shay的代码更优雅)是,您试图在变量存在之前设置它的属性。在调用Invoke WebRequest之前,SessionVariable“$WS”不存在,但您正在尝试在其上方设置.Proxy属性


如果它在某一点上起作用,则您可能以前创建了$WS的实例,因此在测试期间可以使用该对象,但在脚本自上而下处理时,在新运行/干运行时,它还不存在。

Use可以使用以下代码:

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

我没有想过用这种方法来修复它……但这在很多情况下都是非常狡猾和有用的。但是如果他们创建新命令。。。。