Importing PowerShell module in C#

后端 未结 2 1843
长情又很酷
长情又很酷 2020-12-03 15:08

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 s

2条回答
  •  没有蜡笔的小新
    2020-12-03 16:12

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

提交回复
热议问题