在C#中导入PowerShell模块 [英] Importing PowerShell module in C#
问题描述
我正在尝试编写一些C#代码以使用PowerShell与Lync进行交互,并且在执行Lync cmdlet之前,我需要导入Lync模块。但是,我的代码似乎没有导入该模块,并且不断出现找不到get-csuser命令异常。这是我的代码:
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);
}
任何想法如何导入Lync模块?
Any idea how can I import the Lync module?
推荐答案
知道了,需要通过其完整路径导入模块,还需要64位Powershell和32位Powershell的执行策略设置为不受限制(或视情况而定,不是受限制的任何内容)。代码如下:
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);
}
}
这篇关于在C#中导入PowerShell模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!