With the new version of PowerShell Universal Dashboard, you can now create simple REST APIs that execute PowerShell when they are invoked. New cmdlets make it easy to create endpoints and stand up a new REST API server.
Creating a simple endpoint
Assume that we are creating a REST API for local processes on a machine. The first endpoint we will want will be an endpoint to return running processes on the target machine. We can do this in a local PowerShell session with Get-Process. In order to create a REST API around this cmdlet, we can use the new New-UDEndpoint cmdlet generate this endpoint.
To invoke this endpoint we would need to start a new REST API server and then could use Invoke-RestMethod to return our result.
Endpoints can take data from the URL
REST APIs typically gather resource information from the URL that they are provided. For example, we may want to return a single process or stop a single process. We would need to know the ID of that process. In order to achieve this, we can create a URL with New-UDEndpoint that contains variable data. We use the colon to denote a part of the URL that should be treated like a variable. This variable is then passed into the script block as a parameter.
Endpoints can take data from the body
In addition to taking data from the URL of a request, the endpoints can also take data from the HTTP request body. Typically, POST methods will provide data in this manner. UD supports form encoded data as well as any type of string data. Form data will be automatically decoded and passed in as parameters to the script block.
Additionally, any string can be passed into the endpoint via the Body parameter and deserialized within the endpoint. This is useful for deserializing XML and JSON.
Running Endpoint Servers
Endpoint servers can be run using Start-UDRestApi. This cmdlet starts the same type of ASP.NET Core Kestrel server that Start-UDDashboard provides. The only difference is there is no user interface present with a REST API server. You can also pass endpoints into Start-UDDashboard to provide REST APIs on the same port as a dashboard.
A note on security
Note that this implementation does not yet support authorization or authentication. Be careful when standing up REST APIs that provide sensitive information or allows for malicious activity. Authentication is on the road map for both Dashboards and REST APIs.