Import PowerShell module in C #

I am trying to write C # code to interact with Lync using PowerShell, and I need to import the Lync module before running the Lync cmdlets. However, my code does not seem to import the module, and I continue to get the 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 I can import a Lync module?

+4
source share
2 answers

Upon receiving this, the module must be imported in its full path, and for the execution policy for the 64-bit command line and 32-bit command line, you must set the value to "Unlimited" (or something else, except limited depending on your case) , Here is 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); } } 
+7
source

Try using the AddCommand method of the PowerShell class.

 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

-2
source

Source: https://habr.com/ru/post/1485850/


All Articles