【发布时间】:2018-12-07 09:11:01
【问题描述】:
我需要在 Visual Studio 控制台中使用 C# 运行 powershell cmdlet。
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();
}
}
}
}
当我运行代码时发生异常:
“Connect-MsolService”一词未被识别为 cmdlet、函数、脚本文件或可运行程序的名称。检查名称的拼写,或者如果包含路径,请验证路径是否正确并重试。
即使当我在 Powershell 中运行命令时它仍然有效。
【问题讨论】:
-
这个错误意味着很可能模块没有被导入。请检查this answer 是否对您有帮助。
标签: c# visual-studio powershell office365 cmdlets