0

I am creating an HTTPListener that will execute some code with data that is POST to the URI the script is listening to:

$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()

The problem that I'm running into is that the listener won't terminate and continue the script even when $sw.elapsed -lt $timeout is $false.

Is there a way I can make the listener terminate after 10 minutes and continue the script?

Montel Edwards
  • 400
  • 5
  • 14
  • 1
    I just use a counter and include an IF statement to catch the counter going over a specific limit, if that's true use the `break` statement to break out of the loop. – user4317867 Mar 20 '17 at 00:55
  • For debugging purpose printout $sw.elapsed along with $timeout and the result for $sw.elapsed -lt $timeout to understand better what is happening in your loop. – athar13 Mar 20 '17 at 01:55
  • @user4317867 can you provide an example? I tested this out and it will still not break the loop.. – Montel Edwards Mar 21 '17 at 02:07

1 Answers1

0

This is part of a script block but the concept works in my case. In my testing, I need exit because this script block runs in a runspace.

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))
user4317867
  • 2,397
  • 4
  • 31
  • 57