REST API to Run PowerShell from a ASP.Net C# Webapp

vchaindz

vchaindz

Posted on March 1, 2023

REST API to Run PowerShell from a ASP.Net C# Webapp

Do you need to run PowerShell scripts from a web application?

I asked myself the same and quickly realized that there are some really nice benefits to doing so.

  1. PowerShell is very flexible, easy to use, and has plenty of integrations built-in or available

  2. REST APIs are the most popular way to integrate applications with web services. Having a REST endpoint to the outside would allow you to consume pre-defined PowerShell scripts from anywhere using a Browser, curl, or any other REST scripting or development language.

  3. You can change the PowerShell script without changing and compiling c# source code

  4. it could run as part of an existing Microsoft IIS server or as a Docker container

So I decided to develop a boilerplate that can be used to on Windows and Linux, as part of an IIS, standalone using IIS express or a Docker container.

In case you know already everything about REST APIs, please skip the next 2 sections and jump to the overview.

Introduction to REST APIs

REST stands for Representational State Transfer. It is an architectural style of web services that defines how web services interact with clients. A REST API is a web service that uses the REST architecture to provide an interface for applications to access web services.

A REST API is a set of web services that allow applications to access data stored on a server. The data is usually in the form of JSON or XML.

REST APIs are becoming increasingly popular because they are easy to use and can be used to access data from multiple sources.

REST APIs allow developers to access data from web services and other sources in a uniform way. This makes it easier to develop applications that require data from multiple sources.

REST APIs are also popular because they are secure and can be used for authentication. Authentication is the process of verifying the identity of a user or a client. REST APIs can be used to authenticate users and restrict access to data.

Benefits of Using a REST API to Run PowerShell

Using a REST API to run PowerShell scripts has several benefits.

First, it is easy to develop a web application using a REST API. The API provides a uniform way to access data, so it is easier to develop applications that require data from multiple sources.

But it’s much harder to develop a whole application in .net. Here comes the PowerShell.

Second, a REST API can be used to authenticate users and restrict access to data. This is important when running PowerShell scripts as they can be used to access sensitive data. It can also nicely be used to hide credentials and make the PowerShell script itself inaccessible from the outside.

Finally, a REST API provides a convenient way to run PowerShell scripts. The API can be used to access data from multiple sources in a uniform way. This makes it easier to develop applications that require data from multiple sources.

Overview of Developing a WebApp with a REST API to Run PowerShell

Developing a web application with a REST API to run PowerShell scripts is a straightforward process. First, the necessary components of the web application must be developed. This includes the C# web application that provides the REST API and the Powershell script.

The components must be coded and integrated into a single web application. The web application can then be run on an IIS server or a Docker container.

C# WebApp component development

The C# web application is the first component of the web application. The C# web application is responsible for providing the interface for the web application. It is also responsible for handling user input, authenticating users, and providing access to data.

Let’s start with a new project — I use Visual Studio Community — ASP.NET Core Web API, so it can run also in a Docker container.

Create New ASP.NET Core Web API

In the next step let’s check “Enable Docker” using the Linux OS and uncheck “Use controllers” to have the most simple Web App.

Enable Docker support and uncheck Use controllers

That produces already a good project structure and we can directly jump into the C# code:

initial project structure

As we want to use PowerShell commands out of the Web application, you need to install 2 packages to fit all needs (IIS and Docker). Therefore jump to the Package Manager Console and install the packages.

install-package System.Management.Automation
run install-package Microsoft.PowerShell.SDK
Enter fullscreen mode Exit fullscreen mode

Program.cs — the Web application itself

The Progam.cs file that comes with the new project contains a sample weather forecast that you can simply overwrite completely.

Here comes the code that:

  1. listens to REST API calls on /pwsh

  2. allows you to send 2 arguments (string) to the PowerShell script

  3. reads the PowerShell script script.ps1 that resides inside of the project

  4. Runs the script.ps1 PowerShell script with the 2 arguments

  5. Returns an error or the PowerShell result

    using System.IO;
    using System.Management.Automation;

    var builder = WebApplication.CreateBuilder(args);

    // Add services to the container.

    var app = builder.Build();

    app.MapGet("/pwsh", (string arg1, string arg2) =>
    {
    string _filePath = Path.GetDirectoryName(System.AppDomain.CurrentDomain.BaseDirectory);
    // read file content
    string myScript = File.ReadAllText(_filePath + "/script.ps1");

    var result = PowerShell.Create().AddScript(myScript)
    .AddParameter("arg1", arg1)
    .AddParameter("arg2", arg2)
    .Invoke();
    if (result.Count > 0)
    {
    foreach (var PSObject in result)
    {
    return PSObject.ToString();

    }

    }
    return "error occured";

    });

    app.Run();

Now you can create the PowerShell script as a new file in the project.

Hint: Of course, you can either use a script path outside of the project folder or overwrite the file later on using docker -v mapping.

Powershell script development

The second component of the web application is the Powershell script. The Powershell script is responsible for executing the PowerShell commands and returning data to the web application.

The script should be developed in such a way that it is able to execute the necessary commands and return the data in a JSON format that can be processed by the web application.

Simply create the script file named script.ps1 in the project folder.

script.ps1 — the PowerShell script

In this example, we use a very simple PowerShell script that only consumes the 2 arguments and returns these as JSON.

param(
       $arg1,
       $arg2
)

$message = "$arg1, $arg2" | convertto-json

return $message
Enter fullscreen mode Exit fullscreen mode

That is already it and you can start testing the web application and the Powershell script that has been developed.

If all goes well it should look like that.

Run the Web application on an IIS server or a Docker container

Once the web application has been coded and integrated with the REST API, the next step is to run the web application on an IIS server or a Docker container. This will allow the web application to be accessed by users from anywhere in the world.

To build the Docker container you can use the Dockerfile created as part of the project.

Simply clone your repository to a system where Docker is installed, copy the Dockerfile from the project folder to one level above and run:

docker build -f Dockerfile -t rest2pwsh .
Enter fullscreen mode Exit fullscreen mode

Now you can run the Docker container

docker run -it --rm -p 8080:80 rest2pwsh
Enter fullscreen mode Exit fullscreen mode

and test it as well with a browser.

Conclusion

In conclusion, using a REST API to run PowerShell scripts is an efficient and secure way to run PowerShell scripts from a web application. The REST API provides a uniform way to access data from multiple sources, which makes it easier to develop applications that require data from multiple sources. It also provides a secure way to run PowerShell scripts as it can be used to authenticate users and restrict access to data.

The process of developing a web application with a REST API to run PowerShell scripts is straightforward. The necessary components of the web application need to be developed, coded, and integrated into a single web application. The web application can then be run on a IIS server or a Docker container.

If you need to run PowerShell scripts from a web application, then using a REST API to run PowerShell is a great solution. With the right approach, you can unlock the benefits of a REST API to run PowerShell with a C# Webapp.

💖 💪 🙅 🚩
vchaindz
vchaindz

Posted on March 1, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related