Sunday, February 5, 2012

Calling Lync Server 2010 Powershell cmdlets from C# (.NET)

To run Lync Server Management Shell cmdlets from C#, we need to import Lync module into our Powershell runspace before calling. We do a similar thing to initialize Exchange Server runspace in C# 
RunspaceConfiguration.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.E2010", out warning);
So same is the case with Lync Server 2010 but slightly different. Here we import Lync Server module rather than adding snap-in to our runspace.


There are 2 solutions.


1.  Run the following command 


    pipeline.Commands.AddScript(@"Import-Module 'C:\Program Files\Common Files\Microsoft Lync Server 2010\Modules\Lync\Lync.psd1'"); 
in your c# code before running the actual cmdlet.  (assuming the Lync server is installed at default location)


2.  Import Lync module using InitialSessionState


This is even better. You need to add the following code at the time of initializing your runspace.

 InitialSessionState iss = InitialSessionState.CreateDefault();
 iss.ImportPSModule(new string[] { "Lync" });
 myRunSpace = RunspaceFactory.CreateRunspace(iss);
 myRunSpace.Open();
Now run any Lync server cmdlet using this runspace (myrunspace).


You could also just create a runspace and run a PowerShell command:
Collection<PSObject> runPowerShellScript()
       {
           Runspace runSpace = RunspaceFactory.CreateRunspace();
           runSpace.Open();
           Pipeline pipeLine = runSpace.CreatePipeline();
           string myPowerShellScript = "Import-Module Lync";
           pipeLine.Commands.AddScript(myPowerShellScript);
           pipeLine.Commands.Add("Out-String");
           Collection<PSObject> resultObjects = pipeLine.Invoke();
           //... run Lync cmdlets using the current runspace
           runSpace.Close();
           return resultObjects;
       }

Enjoy administrating Lync :)

2 comments:

  1. Must there be a Lync server installed on the same machine where the codes are being executed?

    ReplyDelete
  2. Yes, Lync Server must be on same machine where the codes are being executed.
    Otherwise you can try creating a Remote PowerShell Session as described in this blog.

    http://blogs.technet.com/b/csps/archive/2010/06/16/qsremoteaccess.aspx

    ReplyDelete