Simple HTTP api for Executing PowerShell Scripts
[Based on the feedback, I’ve renamed this to HTTP]
There may be scenarios where you don’t need the full interactive experience of PowerShell remoting over PSRP (PowerShell Remoting Protocol), or have the need to execute some PowerShell scripts from a non-Windows system. You could directly code against WS-Man as I’ve blogged about a long time ago, however, it’s quite complicated requiring knowledge of SOAP and WS-Man. In cases where you want to simply invoke a PowerShell script remotely, a REST api is a good choice since all modern programming languages make it simple to perform a HTTP GET operation.
I wrote a simple HTTP Listener in PowerShell script that uses the .Net HttpListener class. You simply start an instance of the listener (requires an elevated prompt to listen on the network) and now you can execute an arbitrary PowerShell command-line and get back the results in a variety of formats.
Once you have the module installed (just copy the HttpListener folder to your Documents\WindowsPowerShell\Modules folder) and imported, you can start an instance by using the Start-HTTPListener commandlet:
By default, I have it set to listen on port 8888 and using Integrated Windows Authentication, but this is all configurable as parameters to the commandlet. Here, I have another PowerShell window open and I execute “get-process powershell”:
Note that I used the –UseDefaultCredentials to ensure I authenticate with my current security context otherwise you’ll get back Access Denied since anonymous access is not supported.
By default, I return the output as JSON. Because the resulting JSON object is large, it’s truncated. The body of the HTTP response is in the Content property, but it’s a byte array. I use the Utf8 .Net class to decode it and show a portion of the JSON:
I can utilize the ConvertFrom-Json to make it more presentable within PowerShell:
Of course, if you’re using a different scripting client such as Python, Perl, or Ruby, then you would use script libraries in those languages to use the JSON version.
If you’re just playing around, you can use the Text formatting to make things more easily readable and resembles what you would get executing the same command line directly in PowerShell:
Other formatting options are available and if you call the HTTP endpoint without any parameters, you’ll get the basic usage information back:
The code is available on TechNet where I also explain a bit more on how the code actually works.
Principal Test Lead PowerShell