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.
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;
}
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 :)