我需要在Visual Studio控制台中使用C#运行PowerShell cmdlets。
当我运行代码时,出现了异常:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Management.Automation;
using System.Threading;
using System.Management.Automation.Runspaces;
using System.Collections.ObjectModel;
using System.Collections;
namespace ConsoleApp1
{
class Program
{
private static string RunScript()
{
Runspace runSpace = RunspaceFactory.CreateRunspace();
runSpace.Open();
Pipeline pipeline = runSpace.CreatePipeline();
Command cmd = new Command("Connect-MsolService");
pipeline.Commands.Add(cmd);
ICollection results = pipeline.Invoke(); // Here exception occurs
runSpace.Close();
StringBuilder stringBuilder = new StringBuilder();
foreach (PSObject obj in results)
{
stringBuilder.AppendLine(obj.ToString());
}
return stringBuilder.ToString();
}
static void Main(string[] args)
{
using (PowerShell PowerShellInstance = PowerShell.Create())
{
Console.WriteLine(RunScript());
Console.ReadKey();
}
}
}
}
当我运行代码时,出现了异常:
尽管在PowerShell中运行命令时它是有效的。该cmdlet、函数、脚本文件或可操作程序的名称“Connect-MsolService”未被识别。请检查名称的拼写,或者如果包含路径,请验证路径是否正确,然后重试。