PowerShell错误:基础连接已关闭

时间:2018-09-25 15:06:26

标签: powershell webrequest

我正在尝试使用Invoke-WebRequest cmdlet(第一次)连接到Sharp打印机的Web界面。到目前为止,我的代码如下:

$cred = Get-Credential
$url = 'http://<IP address of printer>/login.html?/main.html'
$login = Invoke-WebRequest $url -SessionVariable printer -Method Get
$login.Forms[0].Fields.element10002 = $cred.UserName
$login.Forms[0].Fields.element10002 = 
$cred.GetNetworkCredential().Password
$mainPage = Invoke-WebRequest -Uri ($url + $login.Forms[0].Action) ` 
    -WebSession $printer -Body $login -Method Post

...但是我一直收到此错误:

Invoke-WebRequest : The underlying connection was closed: The connection
was closed unexpectedly.
At line:6 char:13
+ $mainPage = Invoke-WebRequest -Uri ($url + $login.Forms[0].Action) -W 
...
+             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: 
(System.Net.HttpWebRequest
:HttpWebRequest) [Invoke-WebRequest], WebException
+ FullyQualifiedErrorId : 
WebCmdletWebResponseException,Microsoft.Powe
rShell.Commands.InvokeWebRequestCommand

这行代码不会导致错误:

$login = Invoke-WebRequest $url -SessionVariable printer -Method Get

但这行是:

$mainPage = Invoke-WebRequest -Uri ($url + $login.Forms[0].Action) ` 
    -WebSession $printer -Body $login -Method Post

我在Windows 7机器上使用PS版本5.1和Tls12。经过一番谷歌搜索之后,似乎这个问题可能与Tls的版本有关。但我不确定将其更改为什么。

有人有什么想法吗? -@leah_cyberpadawan

1 个答案:

答案 0 :(得分:1)

在使用可能支持自签名证书或仅支持TLS 1.2的端点时,以下两种解决方案对我有用:

[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor [System.Net.SecurityProtocolType]::Tls12
Add-Type -TypeDefinition @'
using System.Net;
using System.Security.Cryptography.X509Certificates;
public class TrustAllCertsPolicy : ICertificatePolicy
{
    public bool CheckValidationResult(ServicePoint sp, X509Certificate cert, WebRequest req, int certProblem)
    {
        return true;
    }
}
'@
[System.Net.ServicePointManager]::CertificatePolicy = New-Object -TypeName TrustAllCertsPolicy

[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor [System.Net.SecurityProtocolType]::Tls12
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}