在PowerShell版本2.0中调用Web请求超时

时间:2014-08-05 10:41:41

标签: powershell

这是继我之前的一个查询之前Invoke-WebRequest equivalent in PowerShell v2

我试图运行以下脚本,它运行2-3次,但之后我反复得到以下超时错误

异常调用" GetRequestStream"用" 0"参数:"操作超时"

Request Timed Out Error

这是脚本

function Invoke_Workflow {

        param(
        [Parameter(Mandatory=$True)]
        [string]$arg,

        [Parameter(Mandatory=$True)]
        [string]$whostname,

        [Parameter(Mandatory=$True)]
        [string]$uuid,

        [Parameter(Mandatory=$True)]
        [string]$wfname,

        [Parameter(Mandatory=$True)]
        [string]$wpassword,

        [Parameter(Mandatory=$True)]
        [string]$wusername

        )


$body = 
"<wInput>
  <userInputValues>
   <userInputEntry value='$arg' key='stringArgument'/>
  </userInputValues>
  <executionDateAndTime></executionDateAndTime>
  <comments></comments> 
</wInput>"

# Disable certificate validation using certificate policy that ignores all certificates
add-type @"
    using System.Net;
    using System.Security.Cryptography.X509Certificates;

    public class IDontCarePolicy : ICertificatePolicy {
        public IDontCarePolicy() {}
        public bool CheckValidationResult(
            ServicePoint sPoint, X509Certificate cert,
            WebRequest wRequest, int certProb) {
            return true;
        }
    }
"@
[System.Net.ServicePointManager]::CertificatePolicy = new-object IDontCarePolicy 


$password = ConvertTo-SecureString $wfapassword -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential ($wfausername, $password)

$request = [System.Net.WebRequest]::Create($URI1)
$request.ContentType = "application/xml"
$request.Method = "POST"
$request.Credentials = $credential

# $request | Get-Member  for a list of methods and properties 

try
{

$request.ServicePoint.MaxIdleTime = 5000;
$request.ServicePoint.ConnectionLeaseTimeout = 5000;
    $requestStream = $request.GetRequestStream()
    $streamWriter = New-Object System.IO.StreamWriter($requestStream)
    $streamWriter.Write($body)
}

finally
{
    if ($null -ne $streamWriter) { $streamWriter.Dispose() }
    if ($null -ne $requestStream) { $requestStream.Dispose() }
}

$res = $request.GetResponse()

$request.Abort()


}

1 个答案:

答案 0 :(得分:3)

问题很可能与默认的Servicepoint连接限制有关,即2。

您可以增加它(以下示例为10)并且如果您在单个PowerShell会话中发出许多请求,则在到达设置连接之前添加对当前连接计数的检查并清除它们(下面的示例为8)限制:

$request.ServicePoint.ConnectionLimit =10;
$conn=$request.ServicePoint.CurrentConnections
    If ($conn -ge 8) {
    $request.ServicePoint.CloseConnectionGroup("")
}