简体   繁体   English

在 C# 中运行 PowerShell cmdlet

[英]Running PowerShell cmdlets in C#

I need to run powershell cmdlets using C# in Visual Studio Console.我需要在 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();
            }
        }
    }
}

When I run the code an Exception occurs:当我运行代码时发生异常:

The term 'Connect-MsolService' is not recognized as the name of a cmdlet, function, script file, or operable program.术语“Connect-MsolService”不被识别为 cmdlet、函数、脚本文件或可运行程序的名称。 Check the spelling of the name, or if a path was included, verify that the path is correct and try again.检查名称的拼写,或者如果包含路径,请验证路径是否正确,然后重试。

Even though it works when I run the commands in Powershell.即使当我在 Powershell 中运行命令时它也能工作。

Try to use PowerShell instance, like this:尝试使用 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();

You are executing it as a CMD command, not as a powershell command.您将它作为 CMD 命令执行,而不是作为 powershell 命令执行。 You have to execute it over an Powershell instance.您必须在 Powershell 实例上执行它。 Check executing-powershell-scripts-from-c .检查execution-powershell-scripts-from-c

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM