# Http Server
$http = [System.Net.HttpListener]::new()
# Hostname and port to listen on
$http.Prefixes.Add("http://localhost:8080/")
# Start the Http Server
$http.Start()
# Log to terminal
if($http.IsListening){write-host "Ready! $($http.Prefixes)" -f 'green'}
# INFINTE LOOP
# Used to listen for requests
while ($http.IsListening) {
# Get Request Url
# When a request is made in a web browser the GetContext() method will retuen the request url
# Our ROUTE EXAMPLE's will use this to decide how to respond
$context = $http.GetContext()
# ROUTE EXAMPLE 1
if ($context.Request.RawUrl -eq '/') {
# We can log the request to the terminal
write-host "A request has been made from $($context.Request.UserHostAddress) for $($context.Request.Url)" -f Magenta
# the html/data you want to send to the browser
# you could replace this with ( Get-Content "C:\some\path\index.html" | Out-String )
[string]$html = "<h1>A Powershell Webserver</h1><p>Root Route</p>"
#resposed to the request
$buffer = [System.Text.Encoding]::UTF8.GetBytes($html) # convert htmtl to bytes
$context.Response.ContentLength64 = $buffer.Length
$context.Response.OutputStream.Write($buffer, 0, $buffer.Length) #stream to broswer
$context.Response.OutputStream.Close() # close the respose
}
# ROUTE EXAMPLE 2
if ($context.Request.RawUrl -eq '/some/path') {
# We can log the request to the terminal
write-host "A request has been made from $($context.Request.UserHostAddress) for $($context.Request.Url)" -f Magenta
# the html/data you want to send to the browser
# you could replace this with ( Get-Content "C:\some\path\index.html" | Out-String )
[string]$html = "<h1>A Powershell Webserver</h1><p>Some Other Route</p>"
#resposed to the request
$buffer = [System.Text.Encoding]::UTF8.GetBytes($html) # convert htmtl to bytes
$context.Response.ContentLength64 = $buffer.Length
$context.Response.OutputStream.Write($buffer, 0, $buffer.Length) #stream to broswer
$context.Response.OutputStream.Close() # close the respose
}
# powershell will continue looping and listen for new requests...
}
# Note:
# To end the loop you have to kill the powershell terminal. ctrl-c wont work :/
-
-
Save lazywinadmin/68aeb698110092dc6a7f926857ee90dc to your computer and use it in GitHub Desktop.
A Basic Powershell Webserver
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment