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:
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);
Pipeline pipeLine = myRunspace.CreatePipeline();
pipeLine.Commands.AddScript(scriptText); // Pass in the script text on the fly
Collection<PSObject> cmdResults = pipeLine.Invoke();
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!