powershell - 从 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>();
}
}
}
解决方案
当您对 进行连续调用时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
推荐阅读
- django - 在多个视图中重用查询集
- python - Python 中的 Excel AVERAGEIF 使用替代表格布局
- go - 写入 CON(Windows 控制台)不会打印到 STDOUT(控制台)
- firebase - 图片网址为空
- javascript - React 路由更改 URL 但不加载组件
- angular - Angular 9 - 解析给定网址的每个参数
- elasticsearch - 尝试过滤该字段可能不存在的一些 Elasticsearch 结果
- python - 如何修复 langdetect 不稳定的结果
- javascript - 节点:使用 promise.all() 来并行调用 API?
- ios - 如何使用 Rx 在 tableView 中使用多个单元格?