术语' New-CsOnlineSession'不被识别为cmdlet的名称

时间:2015-01-28 09:17:26

标签: c# powershell

我正在尝试从c#运行power shell脚本。 仅在运行power shell脚本时,它会成功运行。但是,在尝试从c#运行相同的脚本时。我收到错误“术语'New-CsOnlineSession'未被识别为cmdlet的名称”

以下是代码:

          public static void GetLyncUsers(string userName, string password)
        {
            using (PowerShell powerShellInstance = PowerShell.Create())
            {

                var script = string.Format("$Username =\"{0}\"\n" +
                                           "$Password =\"{1}\"\n" +
                                           "$secpasswd = ConvertTo-SecureString $Password -AsPlainText -Force\n" +
                                           "$cred = new-Object System.Management.Automation.PSCredential ($Username  , $secpasswd)\n" +
                                           "$CSSession = New-CsOnlineSession -Credential $cred\n" +
                                           "Import-PSSession $CSSession -AllowClobber\n" +
                                           "Get-CsOnlineUser", userName, password);

                // use "AddScript" to add the contents of a script file to the end of the execution pipeline.
                // use "AddCommand" to add individual commands/cmdlets to the end of the execution pipeline.

                powerShellInstance.AddScript(script);


                // use "AddParameter" to add a single parameter to the last command/script on the pipeline.


                // invoke execution on the pipeline (collecting output)
                Collection<PSObject> psOutput = powerShellInstance.Invoke();

                // check the other output streams (for example, the error stream)
                if (powerShellInstance.Streams.Error.Count > 0)
                {
                    // I am getting this error 
                  //The term 'New-CsOnlineSession' is not recognized as the name of a cmdlet
                }
        }

我有什么遗失的吗?我是PowerShell的新手。

2 个答案:

答案 0 :(得分:1)

<强>解决方案

using (PowerShell powerShellInstance = PowerShell.Create())
{    
    // Import-Module lynconlineconnector
    powershellInstance.Commands
        .AddCommand("Import-Module")
        .AddArgument("lynconlineconnector");

// rest of your code ....

<强>为什么吗

在powershell v3及更高版本中运行交互式会话时,主机会捕获CommandNotFound,并搜索所有已知位置中的每个模块。如果找到该命令,它会自动加载模块,并正常进行。

在C#中运行相同的脚本时,CommandNotFound异常不会被捕获,因此您会收到错误。

相关问题:

PowerShell - How to Import-Module in a Runspace

#PSTip Cmdlet Discovery and Module auto-loading

答案 1 :(得分:0)

我遇到了同样的问题。您必须按照Technet

中的说明安装Lync / Skype For Business Online Connector
  

安装程序会复制Skype for Business Online Connector   模块(和New-CsOnlineSession cmdlet)到本地计算机。