代码之家  ›  专栏  ›  技术社区  ›  Sameer

术语“New-CsOnlineSession”无法识别为cmdlet的名称

  •  1
  • Sameer  · 技术社区  · 11 年前

    我正在尝试从c#运行一个powershell脚本。 仅运行powershell脚本时,它会成功运行。但是,在尝试从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 回复  |  直到 11 年前
        1
  •  2
  •   Community Mohan Dere    9 年前

    解决方案 :

    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

        2
  •  0
  •   Edgar    9 年前

    我遇到了同样的问题。您必须按照中的说明安装Lync/Skype For Business Online Connector Technet

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