【发布时间】:2021-11-14 07:28:14
【问题描述】:
我正在尝试从 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>();
}
}
}
【问题讨论】:
-
Get-MailUser是ExchangePowerShell 模块的一部分。您正在安装具有Get-EXOMailboxcmdlet 的ExchangeOnlineManagement模块。 -
你需要在不同的命令之间调用
AddStatement() -
@Theo 啊啊啊...是的。这可行,但使用该模块我无法添加/更新邮箱或联系人,只能获取它们。这就是 Powershell SDK nuget。使用桌面版本,我可以整天添加/更新。回到绘图板:(
标签: powershell exchange-server runspace