Calling PowerShell from C#

Lately I have been on a web service that automates creating AD entities and provisioning Lync. It does this by making back-end calls to a PowerShell script. That was the concept and it works very well. The only problem I had at first was figuring out how to call the PowerShell script from C#. I did what any developer would do and turned to Bing to search the Internet. I didn’t find a complete answer but I did find enough bits and pieces to do what I wanted to do. So with my experience in mind I am going to show you how to run your PowerShell scripts from a C# application.


To make this code work you will need to include references in you project to System.Management.Automation and System.Management.Automation.Runspaces.


Note the line that reads ps.AddScript(@”import-module Lync”);”. You will need this so that the shell will load the Lync comandlets. You can also put all of your routines into one script as seperate functions then load our custom script using this line of code.


private string RunScript(string scriptText)


{


PowerShell ps;


// Create the PowerShell object

ps = PowerShell.Create();

// Add command to laod OCS modules so that the CS cmdlets will work

ps.AddScript(@”import-module Lync”);

ps.Invoke();

// Add the PowerShell script to be run

ps.AddScript(scriptText);

ps.Commands.AddCommand(“Out-String”);

// execute the script

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

StringBuilder stringBuilder = new StringBuilder();

// convert the script result into a single string

foreach (PSObject obj in results)

{

stringBuilder.Append(obj.ToString());

}

// convert the erros into a single string

foreach (ErrorRecord error in ps.Streams.Error)

{

//stringBuilder.Append(string.Format(“Error in script : {0} “, error.ToString()));

stringBuilder.Append(error.ToString());

}

return (stringBuilder.ToString());

}

 

I hope this helps you. Automating Lync using PowerShell adds an awesome tool to your repertoire.

Some Links for the New Year

One of my New Year’s resolutions is to blog more often as I have been lax lately. My goal is to blog about Speech Server as well as the things that I am working on. This means that I will also be blogging about FreeSWITCH, UCMA, PowerShell and Lync administration with PowerShell. My goal is shorter blog posts but lots more of them. With that in mind here are some links to get you started in the new year.


Some Lync Developer links 


Lync PowerShell


Lync powerShell Forum


Enjoy.