10

I'm trying to write some C# code to interact with Lync using PowerShell, and I need to import the Lync module before executing the Lync cmdlets. However, my code doesn't seem to import the module and I keep getting a "get-csuser command not found" exception. Here is my code:

PowerShell ps = PowerShell.Create();
ps.AddScript(@"import-module Lync");
ps.Invoke();
ps.Commands.AddCommand("Get-csuser");
foreach (PSObject result in ps.Invoke())
{
    Console.WriteLine(result.Members["Name"].Value);
}

Any idea how can I import the Lync module?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
NullPointer
  • 2,084
  • 7
  • 24
  • 38

2 Answers2

16

Got it, the module needs to be imported by its full path, and also the execution policy for both 64-bit powershell and 32-bit powershell need to be set to Unrestricted (or anything other than restricted depending on your case). Here's the code:

static void Main(string[] args)
{
    InitialSessionState initial = InitialSessionState.CreateDefault();
    initial.ImportPSModule(new string[] {"C:\\Program Files\\Common Files\\Microsoft Lync Server 2010\\Modules\\Lync\\Lync.psd1"} );
    Runspace runspace = RunspaceFactory.CreateRunspace(initial);
    runspace.Open();     
    PowerShell ps = PowerShell.Create();
    ps.Runspace = runspace;
    ps.Commands.AddCommand("Get-csuser");

    foreach (PSObject result in ps.Invoke())
    {
        Console.WriteLine(result.Members["Identity"].Value);
    }
}
abatishchev
  • 98,240
  • 88
  • 296
  • 433
NullPointer
  • 2,084
  • 7
  • 24
  • 38
-3

Try to use the PowerShell class AddCommand method.

ps.AddCommand("import-module Lync");

Or you can use the Runspace class, you can find an example here : http://www.codeproject.com/Articles/18229/How-to-run-PowerShell-scripts-from-C

deryck
  • 70
  • 1
  • 3
  • No joy, I've tried that before too. ps.AddCommand("import-module") followed by ps.AddArgument("Lync"); – NullPointer Jun 12 '13 at 16:44
  • It only says, that term is not recognized as the name of a cmdlet, function, script file or operable program. So module should be added another way. – JayDee Jun 22 '20 at 13:05