Search This Blog

Monday, 19 September 2016

Powershell webserver

I needed a VERY basic web server today to test a load balancer on a new server node.  All it needed to do it serve an HTTP 200 so the load balancer thinks there is a server there, or simply not respond so the load balancer thinks the server has gone away.

The full application stack is not yet available from development, so I adapted a few scripts I found online to create a powershell HTTP "server"



$ServerCode = {
    $listener = New-Object System.Net.HttpListener
    $listener.Prefixes.Add('http://+:80/')

    $listener.Start()

    while ($listener.IsListening) {

        $context = $listener.GetContext()
        $request = $context.Request
        $response = $context.Response
        $message = "OK"
        [byte[]] $buffer = [System.Text.Encoding]::UTF8.GetBytes($message)
        $response.ContentLength64 = $buffer.length
        $response.StatusCode = 200
        $output = $response.OutputStream
        $output.Write($buffer, 0, $buffer.length)
        $output.Close()
    }

    $listener.Stop()
}
  
$serverJob = Start-Job $ServerCode
$serverJobID = ($serverJob).Id
Write-Host "Server started as job ID $serverJobID"
Write-Host "Use 'stop-job $serverJobID' and 'remove-job $serverJobID' after server has completed to tidy up"



Once you're done, you can use stop-job, although you'll need to send a http request to the listener before the job will stop.  remove-job simply cleans up the job list once the job has stopped.  get-job can be used to query the job list

No comments:

Post a Comment