在Azure AD中从C#应用程序运行PowerShell脚本。
添加以下DLL引用
- System.Management.Automation
- Microsoft.Online.Administration.Automation.PSModule.Resources
- Microsoft.Online.Administration.Automation.PSModule
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript("Import-Module AzureAD -Force;");
pipeline.Commands.AddScript("$password = ConvertTo-SecureString " + "\"abc1234\"" + " -AsPlainText -Force");
pipeline.Commands.AddScript("$Cred = New-Object System.Management.Automation.PSCredential (" + "\"abc@abc.com\"" + ", $password)");
pipeline.Commands.AddScript("Connect-AzureAD -Credential $Cred");
pipeline.Commands.AddScript("Get-AzureADApplication -Filter " + "\"DisplayName eq " + "\'PortalTestApp\'" + "\"");
var result = pipeline.Invoke();
遇到错误:
“Connect-AzureAD”这个名称无法识别为 cmdlet、函数、脚本文件或可操作的程序。请检查名称的拼写,或者如果包含路径,请验证路径是否正确,然后重试。
Install-Module AzureAD
命令? - MikeImport-Module AzureAD -Force
,你在错误流中得到了什么?(例如:Console.WriteLine(string.Join("\n", pipeline.Error.ReadToEnd().Select(err => err.ToString())));
) - Philippe Signoret