首页 文章

在C#中运行PowerShell cmdlet

提问于
浏览
1

我需要在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中运行命令时也能正常工作 .

1 回答

  • 0

    您将其作为CMD命令执行,而不是作为powershell命令执行 . 您必须通过Powershell实例执行它 . 检查executing-powershell-scripts-from-c .

相关问题