c# - 在 C# 中运行 PowerShell cmdlet

标签 c# visual-studio powershell office365 powershell-cmdlet

我需要在 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();
            }
        }
    }
}

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

The term 'Connect-MsolService' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

即使当我在 Powershell 中运行命令时它仍然有效。

最佳答案

尝试使用 PowerShell 实例,如下所示:

InitialSessionState iss = InitialSessionState.CreateDefault();
iss.ImportPSModule(new[] { "MSOnline" });
iss.LanguageMode = PSLanguageMode.FullLanguage;
var _o365Runspace = RunspaceFactory.CreateRunspace(iss);
_o365Runspace.Open();
var _o365Shell = PowerShell.Create();
_o365Shell.Runspace = _o365Runspace;
var connect = new Command("Connect-MsolService");
connect.Parameters.Add("Credential", new PSCredential("logon@name",
        GetSecureString("Password"));
_o365Shell.Commands.AddCommand(connect);
// add some msol commands to _o365Shell.Commands as well
_o365Shell.Invoke();

关于c# - 在 C# 中运行 PowerShell cmdlet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51080285/

相关文章:

c# - 有效去除用户评论中的恶语

c# - 关闭任务托盘应用程序

c# - 如何将 For 语句转换为 LINQ

powershell - 在Powershell中使用2个数组创建具有多个值的哈希

powershell - 循环期间变量未重置会产生误导性输出

c# - 在 Model ValidationProvider 中使用反射有多糟糕?

c# 从另一个线程而不是 UI 线程调用 backgroundWorker

python - 在 Windows 上安装 rasa

C# - 网站 - SQL Select 语句

powershell - 使用 Powershell 执行带参数的 exe