Hosting PowerShell in ASP.NET

Having read this post. I just couldn’t resist :) Of course, this is not a full featured PS host – but simple commands like get-process work and by caching the runspace you keep state between the commands you invoke.

Needless to say that such a page should be properly secured….

<%@ Page Language=”C#” %>


<%@ Import Namespace=”System.Management.Automation” %>

<%@ Import Namespace=”System.Management.Automation.Runspaces” %>

<%@ Import Namespace=”System.Collections.ObjectModel” %>


<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN””&gt;


<script runat=”server”>


  protected void _btnInvoke_Click(object sender, EventArgs e)


    Runspace rs = GetRunspace();


    Pipeline cmd = rs.CreatePipeline(_txtCommand.Text);

    Collection<PSObject> results = cmd.Invoke();


    StringBuilder sb = new StringBuilder();

    sb.AppendLine(“Command: “ + _txtCommand.Text);



    foreach (PSObject ps in results)






    _txtOutput.Text += sb.ToString();



  protected Runspace GetRunspace()


    if (Cache[“rs”] == null)


      Runspace rs = RunspaceFactory.CreateRunspace();


      Cache[“rs”] = rs;



    return (Runspace)Cache[“rs”];



  protected void _btnClear_Click(object sender, EventArgs e)


    _txtOutput.Text = “”;




<html xmlns=””&gt;

<head runat=”server”>

  <title>ASP.NET PowerShell</title>


<body style=”font-family: Arial”>

  <form id=”form1″ runat=”server”

    defaultbutton=”_btnInvoke” defaultfocus=”_txtCommand”>




    <br />


    <br />

    <asp:TextBox runat=”server” ID=”_txtCommand” Width=”800px” />

    <br />

    <asp:Button runat=”server” ID=”_btnInvoke” Text=”Invoke”

      OnClick=”_btnInvoke_Click” />

    <asp:Button runat=”server” ID=”_btnClear” Text=”Clear History”

      OnClick=”_btnClear_Click” />

    <br />

    <br />


    <br />

    <asp:TextBox runat=”server” ID=”_txtOutput” Width=”800px” Height=”550px”

      TextMode=”MultiLine” />






This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s