在 C# 中运行 PowerShell cmdlet

sar*_* ks 7 c# powershell cmdlets visual-studio office365

我需要在 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();
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

当我运行代码时发生异常:

术语“Connect-MsolService”不被识别为 cmdlet、函数、脚本文件或可运行程序的名称。检查名称的拼写,或者如果包含路径,请验证路径是否正确,然后重试。

即使当我在 Powershell 中运行命令时它也能工作。

小智 1

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

  • `您正在执行命令提示符,而不是 powershell 命令`嗯?我想说,提到的异常肯定来自 PowerShell,而不是命令提示符。更可能的是所需的模块尚未导入。 (2认同)