While writing few solutions for html code I wanted to test basic html web pages, which I required to check with web server, here PowerShell can be handy to create simple and basic web server to serve html web page for testing purpose.
Download this code basic_webserver_httplistener.ps1 here or it is also available on github.com.
To start below are the details about url of webserver and html codes. It is very basic html code and you can see the result of the same above in the browser.
#html url $url = 'http://localhost:8080/' #html code $htmlCode = @" <!DOCTYPE html> <html> <body> <h1>PowerShell Web Server</h1> <p>Example Web Server with Http Listener</p> </body> </html> "@
Here I am using .net object System.Net.HttpListener to create a basic web server. This object has capability to show the web pages code on the browser. Add the url in the prefixes property and start the listener.
# start basic web server $htmlListener = New-Object System.Net.HttpListener $htmlListener.Prefixes.Add($url) $htmlListener.Start()
Next process is the receive html request and get the response from server.
# process html request $httpContext = $htmlListener.GetContext() $httpResponse = $httpContext.Response
Next convert html code to UTF8 and write it on the http response output stream. You can put while loop here for continuous serving web pages.
# show the HTML code/page to the caller $buffer = [Text.Encoding]::UTF8.GetBytes($htmlCode) $httpResponse.ContentLength64 = $buffer.length $httpResponse.OutputStream.Write($buffer, 0, $buffer.length)
Once you hit the url in the browser, this listener is stopped automatically if you don't use while loop in above code.
#close and stop http response and listener $httpResponse.Close() $htmlListener.Stop()
Useful Articles
Powershell: Change DNS IP addresses remotely on multiple computers using CIM & WMI
Installing, importing and using any module in powershell
Microsoft PowerShell: Check Windows license activation status
Find next available free drive letter using PowerShell
Copy Files with PowerShell Remoting WINRM Protocol
Powershell Find application window state minimized or maximized
How to Install and Use Microsoft PowerShell on Linux
Configure PowerShell remoting between Windows and Linux