Playing around with IIS, .NET and PowerShell, more specifically how to execute PowerShell from a form on a webpage. It turns out actually invoking some PowerShell on server side via a client request is quite easy. Here I am hoping to show an example of the minimum code required to achieve this.
We will create a simple interface like the one below. The button to run code will invoke a PowerShell command on the server. The result of the PowerShell command will be appended to the text box below the button.
The command I am using for testing this with is:
This command will query the pc for its hostname and return it. So after pressing the button the server will run this command and print the result in the text box. The webpage should now look like this.
Only 2 files are required to achieve this, I have chosen to use C# to create this. The .html file required is:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="test.aspx.cs" Inherits="powerWeb.test" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head id="Head1" runat="server">
<title>c# iis powersehll</title>
<form id="form1" runat="server">
<asp:Button ID="resetButton" runat="server" Width="308" Text="Run Code" onClick="runCode" /><br />
<!-- Holds the result of the command -->
<asp:TextBox ID="response" TextMode="MultiLine" Width="600" Height="200" runat="server"></asp:TextBox><br />
And the .aspx.cs file required that goes along with the html is is:
public partial class test : System.Web.UI.Page
//function that runs when the button is pressed
protected void runCode(object sender, EventArgs e)
//create the powershell instance and give it the command we will be executing
var shell = PowerShell.Create();
//build out query string
string query = "$(Get-WmiObject Win32_Computersystem).name";
//add the command specified from the gui
//execute the command and store resutls in results
var results = shell.Invoke();
//for each item in the results we append it ot the response text box on the webpage
foreach (PSObject result in results)
response.Text = Server.HtmlEncode(result.BaseObject.ToString());
Note that you may need to use package manager to install 'System.Management.Automation' as detailed here: https://www.nuget.org/packages/System.Management.Automation
Like stated before the point of this is to provide a minimum example of how to execute PowerShell from IIS and .NET. I plan to expand on this concept to allow some PowerShell to ad automation. So I might get around to posting more on here if I have success with this.