简体   繁体   English

在C#中导入PowerShell模块

[英]Importing PowerShell module in C#

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. 我正在尝试编写一些C#代码以使用PowerShell与Lync进行交互,并且在执行Lync cmdlet之前,我需要导入Lync模块。 However, my code doesn't seem to import the module and I keep getting a "get-csuser command not found" exception. 但是,我的代码似乎没有导入模块,并且不断收到“找不到get-csuser命令”异常。 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? 知道如何导入Lync模块吗?

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). 知道了,该模块需要通过其完整路径导入,并且64位Powershell和32位Powershell的执行策略都需要设置为Unrestricted(或根据情况的不同而不同)。 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);
    }
}

Try to use the PowerShell class AddCommand method. 尝试使用PowerShell类的AddCommand方法。

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 或者您可以使用Runspace类,可以在此处找到示例: http : //www.codeproject.com/Articles/18229/How-to-run-PowerShell-scripts-from-C

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM