我有像这样的PowerShell脚本
$timer = [System.Diagnostics.Stopwatch]::StartNew()
$cookieContainer = New-Object System.Net.CookieContainer
try
{
[system.Net.HttpWebRequest] $authRequest = [system.Net.HttpWebRequest]::Create($authUrl)
$authRequest.CookieContainer = $cookieContainer
$authRequest.Method = "POST";
$authRequest.ContentType = "application/x-www-form-urlencoded";
$byteArray = [System.Text.Encoding]::UTF8.GetBytes($authPostData)
$authRequest.ContentLength = $byteArray.Length
$dataStream = $authRequest.GetRequestStream()
$dataStream.Write($byteArray, 0, $byteArray.Length)
$dataStream.Close()
$authResponse = $authRequest.GetResponse();
但在行$dataStream = $authRequest.GetRequestStream()
中会引发异常:
System.Net.WebException:底层连接已关闭:接收时发生意外错误。 ---> System.IO.IOException:读取操作失败,请参阅内部异常。 ---> System.Management.Automation.PSInvalidOperationException:此线程中没有可用于运行脚本的Runspace。您可以在System.Management.Automation.Runspaces.Runspace类型的DefaultRunspace属性中提供一个。您尝试调用的脚本块是:$ true 在System.Net.Security.SslState.CheckOldKeyDecryptedData(Byte []缓冲区,Int32偏移量,Int32计数) 在System.Net.Security.SslState.CheckEnqueueRead(Byte []缓冲区,Int32偏移量,Int32计数,AsyncProtocolRequest请求) 在System.Net.Security._SslStream.StartReading(Byte []缓冲区,Int32偏移量,Int32计数,AsyncProtocolRequest asyncRequest) 在System.Net.Security._SslStream.ProcessRead(Byte []缓冲区,Int32偏移量,Int32计数,AsyncProtocolRequest asyncRequest) ---内部异常堆栈跟踪结束--- 在System.Net.Security._SslStream.ProcessRead(Byte []缓冲区,Int32偏移量,Int32计数,AsyncProtocolRequest asyncRequest) 在System.Net.TlsStream.Read(Byte []缓冲区,Int32偏移量,Int32大小) 在System.Net.PooledStream.Read(Byte []缓冲区,Int32偏移量,Int32大小) 在System.Net.Connection.SyncRead(HttpWebRequest请求,布尔userRetrievedStream,布尔probeRead) ---内部异常堆栈跟踪结束--- 在System.Net.HttpWebRequest.GetRequestStream(TransportContext& context) 在System.Net.HttpWebRequest.GetRequestStream() at GetRequestStream(Object,Object []) at System.Management.Automation.DotNetAdapter.AuxiliaryMethodInvoke(Object target,Object [] arguments,MethodInformation methodInformation,Object [] originalArguments)
我试图解决它或谷歌,但它没有帮助。我只是不明白为什么它因多线程异常而失败,因为我没有创建任何额外的线程,而且我正确地调用HttpWebRequest
属性,所以它不应该也是内在的例外。
这也很奇怪,因为我有一个" lib-script"文件,我有多个脚本调用它,它看起来像
function GetRequest([string] $url, [System.Net.CookieContainer] $cookieContainer, [string] $postParams, [string] $userAgent)
{
[system.Net.HttpWebRequest] $request = [system.Net.HttpWebRequest]::Create($url)
$request.CookieContainer = $cookieContainer
$request.UserAgent = $userAgent
if (![string]::IsNullOrEmpty($postParams))
{
$request.Method = "POST"
$request.ContentType = "application/x-www-form-urlencoded"
$request.ContentLength = $postParams.Length
[System.IO.TextWriter] $requestWriter = New-Object System.IO.StreamWriter($request.GetrequestStream())
$requestWriter.Write($postParams)
$requestWriter.Close()
$requestWriter.Dispose();
}
return [system.Net.HttpWebRequest] $request
}
function GetContentFromUrl([System.String] $url, [System.Net.CookieContainer] $cookieContainer, [System.String] $postParams, [string] $userAgent)
{
try
{
$request = GetRequest $url $cookieContainer $postParams $userAgent
$Response = $request.GetResponse()
[System.IO.TextReader] $ContentStream = New-Object System.IO.StreamReader($Response.GetResponseStream())
$Content = [System.Web.HttpUtility]::HtmlDecode($ContentStream.ReadToEnd())
$ContentStream.Close()
$Response.Close()
if($Response.StatusCode -ne 200)
{
throw;
}
return $Content
}
catch [System.Net.WebException]
{
try
{
# Write-Host $Error[0] -foregroundcolor "magenta"
$exception = $_.Exception
$status = GetStatusDescription( $exception.Status)
$Error = GetExceptionDetails( $exception)
$errorInfo = GetErrorInfo($exception)
$errorDescription = GetErrorDescription($exception)
$responseText = GetFailedResponseText -exception ($exception)
if($exception.Response -ne $null)
{
$exception.Response.Close()
}
SetResult -result $false -info $errorInfo -properties (GetAdditionalProperties -pingUrl $url -responseUri $exception.Response.ResponseUri -httpResponseStatusCode ($exception.Response.StatusCode) -errorCode ($ErrorCode.WebError) -errorDescription $errorDescription -responseText ($responseText))
Exit
}
catch [System.Exception]
{
[System.String] $resultText = "При получении ответа произошла ошибка :{0} {1} {2} " -f ($status, $exception, $exception.GetType())
SetResult -result $false -info $errorInfo -properties (GetAdditionalProperties -pingUrl $url -resultCount 0 -errorDescription $errorDescription -httpResponseStatusCode 0)
Exit
}
}
}
我从来没有遇到任何问题。其他脚本只是调用GetContent函数并从url接收内容。但是当其他脚本(> 30)工作正常时,它会失败并出现相同的异常。
连接时BeginGetRequestStream
似乎失败了。或类似的东西。
所以我使用了这段代码
Import-Module -name "C:\CommonFunctions.ps1" -Global
$authUrl= 'http://www.someurl.com/somepage'
$authPostData='j_username=useruseruser&j_password=passpasspass&login=%D0%92%D0%BE%D0%B9%D1%82%D0%B8'
$cookieContainer = New-Object System.Net.CookieContainer
$content = GetContentFromUrl $authUrl $cookieContainer #$authPostData
$content
现在它失败了:
[DBG]:PS C:\ Users \ Administrator \ Documents> $ exception.ToString() System.Net.WebException:底层连接已关闭:可以 不建立SSL / TLS安全通道的信任关系。 ---> System.Security.Authentication.AuthenticationException:远程 根据验证程序,证书无效。在 System.Net.Security.SslState.StartSendAuthResetSignal(ProtocolToken message,AsyncProtocolRequest asyncRequest,Exce ption exception)
在System.Net.Security.SslState.StartSendBlob(Byte []传入,Int32 count,AsyncProtocolRequest asyncRequest)at System.Net.Security.SslState.ProcessReceivedBlob(Byte []缓冲区,Int32 count,AsyncProtocolRequest asyncRequest)at System.Net.Security.SslState.StartReceiveBlob(Byte []缓冲区, AsyncProtocolRequest asyncRequest)at System.Net.Security.SslState.StartSendBlob(Byte [] incoming,Int32 count,AsyncProtocolRequest asyncRequest)at System.Net.Security.SslState.ProcessReceivedBlob(Byte []缓冲区,Int32 count,AsyncProtocolRequest asyncRequest)at System.Net.Security.SslState.StartReceiveBlob(Byte []缓冲区, AsyncProtocolRequest asyncRequest)at System.Net.Security.SslState.StartSendBlob(Byte [] incoming,Int32 count,AsyncProtocolRequest asyncRequest)at System.Net.Security.SslState.ProcessReceivedBlob(Byte []缓冲区,Int32 count,AsyncProtocolRequest asyncRequest)at System.Net.Security.SslState.StartReceiveBlob(Byte []缓冲区, AsyncProtocolRequest asyncRequest)at System.Net.Security.SslState.StartSendBlob(Byte [] incoming,Int32 count,AsyncProtocolRequest asyncRequest)at System.Net.Security.SslState.ProcessReceivedBlob(Byte []缓冲区,Int32 count,AsyncProtocolRequest asyncRequest)at System.Net.Security.SslState.StartReceiveBlob(Byte []缓冲区, AsyncProtocolRequest asyncRequest)at System.Net.Security.SslState.StartSendBlob(Byte [] incoming,Int32 count,AsyncProtocolRequest asyncRequest)at System.Net.Security.SslState.ProcessReceivedBlob(Byte []缓冲区,Int32 count,AsyncProtocolRequest asyncRequest)at System.Net.Security.SslState.StartReceiveBlob(Byte []缓冲区, AsyncProtocolRequest asyncRequest)at System.Net.Security.SslState.StartSendBlob(Byte [] incoming,Int32 count,AsyncProtocolRequest asyncRequest)at System.Net.Security.SslState.ForceAuthentication(Boolean receiveFirst, Byte [] buffer,AsyncProtocolRequest asyncRequ est)at System.Net.Security.SslState.ProcessAuthentication(LazyAsyncResult lazyResult)at System.Threading.ExecutionContext.RunInternal(执行上下文 executionContext,ContextCallback回调,Object st ate,Boolean preserveSyncCtx)at System.Threading.ExecutionContext.Run(执行上下文 executionContext,ContextCallback回调,对象状态,Boo lean preserveSyncCtx)at System.Threading.ExecutionContext.Run(执行上下文 executionContext,ContextCallback回调,对象状态)at System.Net.TlsStream.ProcessAuthentication(LazyAsyncResult result)
在System.Net.TlsStream.Write(Byte []缓冲区,Int32偏移量,Int32大小) 在System.Net.PooledStream.Write(Byte []缓冲区,Int32偏移量,Int32 System.Net.ConnectStream.WriteHeaders(Boolean async)的大小) ---内部异常堆栈跟踪的结束---在System.Net.HttpWebRequest.GetRequestStream(TransportContext& context) 在System.Net.HttpWebRequest.GetRequestStream()处 GetRequestStream(Object,Object [])at System.Management.Automation.DotNetAdapter.AuxiliaryMethodInvoke(对象 target,Object [] arguments,MethodInformatio n methodInformation, Object [] originalArguments)
它好多了。我将证书添加到我的查询中。谢谢大家的帮助。