Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Powershell HTTP server in background thread (could be easily killed)
$ServerThreadCode = {
$listener = New-Object System.Net.HttpListener
while ($listener.IsListening) {
$context = $listener.GetContext() # blocks until request is received
$request = $context.Request
$response = $context.Response
$message = "Testing server"
# This will terminate the script. Remove from production!
if ($request.Url -match '/end$') { break }
[byte[]] $buffer = [System.Text.Encoding]::UTF8.GetBytes($message)
$response.ContentLength64 = $buffer.length
$response.StatusCode = 500
$output = $response.OutputStream
$output.Write($buffer, 0, $buffer.length)
$serverJob = Start-Job $ServerThreadCode
Write-Host "Listening..."
Write-Host "Press Ctrl+C to terminate"
[console]::TreatControlCAsInput = $true
# Wait for it all to complete
while ($serverJob.State -eq "Running")
if ([console]::KeyAvailable) {
$key = [system.console]::readkey($true)
if (($key.modifiers -band [consolemodifiers]"control") -and ($key.key -eq "C"))
Write-Host "Terminating..."
$serverJob | Stop-Job
Remove-Job $serverJob
Start-Sleep -s 1
# Getting the information back from the jobs
Get-Job | Receive-Job
Copy link

MasterGroosha commented Jan 1, 2016

Hangs on "Terminating" :(

Copy link

ASfSDlS61TLT6eoP3Qb7 commented Feb 16, 2016

Unfortunately, it indeed hangs on "Terminating..."

Copy link

ASfSDlS61TLT6eoP3Qb7 commented Feb 16, 2016

I managed to stop the listener by a little dirty way:

try { $result = Invoke-WebRequest -Uri "http://localhost:888/end" } catch { Write-Host "Listener ended" }

Copy link

natnael-wubet commented Apr 19, 2017

if this is terminating, you should change the ports and dont forget to run it as administrator
to stop it just press ctrl+c

Copy link

mark05e commented Jul 9, 2022

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment