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”

http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&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);

    sb.AppendLine();

 

    foreach (PSObject ps in results)

    {

      sb.AppendLine(ps.ToString());

    }

 

    sb.AppendLine();

    _txtOutput.Text += sb.ToString();

  }

 

  protected Runspace GetRunspace()

  {

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

    {

      Runspace rs = RunspaceFactory.CreateRunspace();

      rs.Open();

      Cache[“rs”] = rs;

    }

 

    return (Runspace)Cache[“rs”];

  }

 

  protected void _btnClear_Click(object sender, EventArgs e)

  {

    _txtOutput.Text = “”;

  }

</script>

 

<html xmlns=”http://www.w3.org/1999/xhtml”&gt;

<head runat=”server”>

  <title>ASP.NET PowerShell</title>

</head>

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

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

    defaultbutton=”_btnInvoke” defaultfocus=”_txtCommand”>

    <div>

      <h1>

        PowerShell</h1>

    <br />

    Command:

    <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 />

    History:

    <br />

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

      TextMode=”MultiLine” />

    </div>

  </form>

</body>

</html>

 

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

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

WordPress.com Logo

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

Facebook photo

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

Connecting to %s