从Web API连接并运行PowerShell命令



我正在尝试从Web Api运行PowerShell命令。我得到的都是这个错误术语"Get-MailUser"不能被识别为cmdlet、函数、脚本文件或可执行程序的名称。我可以从PowerShell 7命令运行相同的代码,它工作得很好。我在项目中使用微软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>();
}
}
}

当你连续调用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

最新更新