Skip to content

Instantly share code, notes, and snippets.

@leonletto
Forked from 19WAS85/powershell-web-server.ps1
Last active March 5, 2018 13:37
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leonletto/10507344 to your computer and use it in GitHub Desktop.
Save leonletto/10507344 to your computer and use it in GitHub Desktop.
Simple Windows WebServer for testing that ports are working
### Basic webserver to check ports are available
##
## copy into a directory - for example c:\test
## open a command prompt and cd into that directory
## run 'powershell' - enter
##
## the first time you run powershell you will need to allow scripts to run
## to do this type 'Set-ExecutionPolicy UnRestricted' - enter
##
## Now type '.\powershell-web-server.ps1 2010' - enter
## This will start a web server on port 2010 which you can connect
## to if your firewall rules are correct.
##
## REMEMBER to run --Set-ExecutionPolicy Restricted-- when done your testing
##
## Enjoy!
## Leon
param (
[string]$port = $(throw "-port is required.")
)
$myres1 = '<html><body>Server is accessible from port '
$myres2 = '<br><a href="/end">Click here to Quit</a><BR>REMEMBER to run'
$myres3 = ' --Set-ExecutionPolicy Restricted-- when done your testing</body></html>'
$resp1 = $myres1 + $port + $myres2 + $myres3
$myredir = '<html><head><meta http-equiv="refresh" content="0; url=/" /></head><body></body></html>'
$routes = @{
"/" = { return $resp1 };
"/end" = { return $myredir }
}
$url = "http://+:$port/"
$listener = New-Object System.Net.HttpListener
$listener.Prefixes.Add($url)
$listener.Start()
Write-Host "Listening at $url..."
while ($listener.IsListening)
{
$context = $listener.GetContext()
$requestUrl = $context.Request.Url
$response = $context.Response
Write-Host ''
Write-Host "> $requestUrl"
$route = $routes.Get_Item($requestUrl.LocalPath)
if ($requestUrl.LocalPath -match '/end') {
$content = & $route
$buffer = [System.Text.Encoding]::UTF8.GetBytes($content)
$response.ContentLength64 = $buffer.Length
$response.OutputStream.Write($buffer, 0, $buffer.Length)
break
}
elseif ($route -eq $null)
{
$response.StatusCode = 404
}
else
{
$content = & $route
$buffer = [System.Text.Encoding]::UTF8.GetBytes($content)
$response.ContentLength64 = $buffer.Length
$response.OutputStream.Write($buffer, 0, $buffer.Length)
}
$response.Close()
$responseStatus = $response.StatusCode
Write-Host "< $responseStatus"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment