首页 > 解决方案 > 从 Web API 连接并运行 PowerShell 命令

问题描述

我正在尝试从 Web Api 运行 PowerShell 命令。我得到的只是这个错误 术语“Get-MailUser”未被识别为 cmdlet、函数、脚本文件或可执行程序的名称。我可以从 PowerShell 7 命令运行相同的代码,并且运行良好。我在项目中使用 Microsoft PowerShell SDK,显示级别为 7.1。任何帮助将不胜感激!

这是我正在使用的代码。

          if (powershell == null)
            {
                using (Runspace runspace = RunspaceFactory.CreateRunspace())
                {
                    runspace.Open();
                    powershell = PowerShell.Create();
                    powershell.Runspace = runspace;

                    PSCommand command = new PSCommand();
                    command.AddCommand("Set-ExecutionPolicy").AddArgument("RemoteSigned");
                    command.AddCommand("New-PSSession");
                    command.AddCommand("Import-Module").AddParameter("Name", "PowerShellGet");
                    command.AddCommand("Install-Module").AddParameter("Name", "ExchangeOnlineManagement").AddParameter("Force");
                    command.AddCommand("Import-Module").AddParameter("Name", "ExchangeOnlineManagement");
                    command.AddCommand("Connect-ExchangeOnline").AddParameter("CertificateThumbPrint", "mythumbprint")
                                                                   .AddParameter("AppId", "my app id")
                                                                   .AddParameter("Organization", "mycompany.onmicrosoft.com");
                    command.AddCommand("Get-MailUser").AddParameter("Identity", "myemailaddress");

                    powershell.Commands = command;
                    // Collection<PSObject> results = powershell.Invoke();
                    var t1 = powershell.Invoke<PSSession>();
                }
            }
        }

标签: powershellexchange-serverrunspace

解决方案


当您对 进行连续调用时AddCommand,您实际上是在组成一个管道- 因此与您在 PowerShell 中的代码等效的是:

Set-ExecutionPolicy RemoteSigned |New-PSSession |Import-Module -Name PowerShellGet |Install-Module -Name ExchangeOnlineManagement -Force |Import-Module -Name ExchangeOnlineManagement |Connect-ExchangeOnline -CertificateThumbPrint mythumbprint -AppId "my app id" -Organization mycompany.onmicrosoft.com |Get-MailUser -Identity myemailaddress

...这可能不是你想要的。

请记住AddStatement()在命令之间调用:

command.AddCommand("Install-Module").AddParameter("Name", "ExchangeOnlineManagement").AddParameter("Force");
command.AddStatement();
command.AddCommand("Import-Module").AddParameter("Name", "ExchangeOnlineManagement");
command.AddStatement();
// ... and so forth

推荐阅读