PowerShell Script with ASP.NET and Console Application

I have two projects that need to incorporate Windows PowerShell, Exchange Management Shell and ActiveRoles Management Shell for AD (by Quest) in a ASP.NET and a Console Application recently, so I started to look for information about PowerShell scripting with .NET and below are two important articles in my opinion:

  1. HOWTO: Using PowerShell in ASP.NET (.NET Framework 2.0)

The first article explains the most challenging issues in hosting PowerShell scripting with ASP.NET - Security context and permission and describe three common optioins. The second article describes the logic and tips in writing PowerShell in .NET managed code application.

I wrote a small class to execute the PowerShell script, by passing in various script text on the fly. Below is a small code snippet:

  private const string PS_SNAP_IN_MICROSOFT = "Microsoft.Exchange.Management.PowerShell.Admin";
  private const string PS_SNAP_IN_QUEST = "Quest.ActiveRoles.AdManagement";

            RunspaceConfiguration rsConfig = RunspaceConfiguration.Create();
            PSSnapInException snapInException = null;
            rsConfig.AddPSSnapIn(PS_SNAP_IN_MICROSOFT, out snapInException); // Add Exchange Mgmt SnapIn
            rsConfig.AddPSSnapIn(PS_SNAP_IN_QUEST, out snapInException);  // Add Quest Mgmt SnapIn
           
            Runspace myRunspace = RunspaceFactory.CreateRunspace(rsConfig);
            myRunspace.Open();

            Pipeline pipeLine = myRunspace.CreatePipeline();
            pipeLine.Commands.AddScript(scriptText);  // Pass in the script text on the fly
            pipeLine.Commands.Add("Out-String"); 

            Collection<PSObject> cmdResults = pipeLine.Invoke();

            myRunspace.Close();

After preparing these PowerShell scripting in .NET app, I'd suggest to stick with PowerShell because it's handy and flexible. I'd prefer it over DirectoryServices or CDOEXM commands. :) Read the useful articles mentioned above in sequence then you are ready to start coding!

Regards,
Colt

13 Comments

Comments have been disabled for this content.