2017-03-19 80 views
0

我創建將是POST數據執行一些代碼的HTTPListener到URI腳本聽:HTTPListerner不響應while語句

$timeout = New-Timespan -Minutes 10 
$sw = [Diagnostics.Stopwatch]::StartNew() 
$listener = New-Object System.Net.HttpListener 
$listener.Prefixes.Add('http://+:8912/') 

while ($sw.elapsed -lt $timeout) { 
    $listener.Start() 
    $context = $listener.GetContext() 
    $request = $context.Request 
    $response = $context.Response 

    $InputStream = New-Object System.IO.StreamReader $Context.Request.InputStream 
    # $msg = $InputStream.ReadToEnd() | ConvertFrom-Json 

    if ($request.Url -match '/post$') { 
    $response.ContentType = 'application/json' 
    # $msg | Write-Output 
    $message = "Message Received" 
    $raw = $InputStream.ReadToEnd() 
    $raw | Write-Output 
    $raw | Out-file -FilePath C:\msg.json 
    } 

    if ($request.Url -match '/end$') { break } 

    [byte[]] $buffer = [System.Text.Encoding]::UTF8.GetBytes($message) 
    $response.ContentLength64 = $buffer.Length 
    $output = $response.OutputStream 
    $output.Write($buffer, 0, $buffer.Length) 
    $output.Close() 
} 
$listener.Stop() 

是我遇到的是問題即使當$sw.elapsed -lt $timeout$false時,收聽者也不會終止並繼續該腳本。

有沒有辦法讓偵聽器在10分鐘後終止並繼續運行腳本?

+1

我只是使用一個計數器,幷包含一個IF語句來捕捉計數器超過特定的限制,如果這是真的使用'break'語句打破循環。 – user4317867

+0

爲了調試目的,打印輸出$ sw.elapsed和$ timeout以及$ sw.elapsed -lt $ timeout的結果以更好地理解您的循環中發生了什麼。 – athar13

+0

@ user4317867你能提供一個例子嗎?我測試了這一點,它仍然不會打破循環.. –

回答

0

這是腳本塊的一部分,但這個概念在我的情況下工作。在我的測試中,我需要exit,因爲此腳本塊在運行空間中運行。

do{$counter++ 

Start-Sleep -Seconds 1 
IF($counter -ge 600){#"Waited too long" 
     [PsCustomObject]@{ 
      "Server" = $server 
      "Status" = "FailedToReboot!" 
      }#end custom logging object 
     exit 
    }#end if. 
}#end do loop. 
until (-not (Test-Connection -ComputerName $server -Count 1 -Quiet))