在C#中运行PowerShell命令的方法

8
我需要在Visual Studio控制台中使用C#运行PowerShell cmdlets。
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();
            }
        }
    }
}

当我运行代码时,出现了异常:

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

尽管在PowerShell中运行命令时它是有效的。

2
这个错误意味着很可能模块还没有被导入。请检查一下 这个答案 是否能帮到您。 - Robert Dyjas
2个回答

3

尝试使用 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();

1
您正在将其作为CMD命令执行,而不是PowerShell命令。您必须在PowerShell实例上执行它。 请参阅从c中执行PowerShell脚本

2
你正在执行命令提示符,而不是PowerShell命令。嗯?我会说所提到的异常肯定来自PowerShell而不是命令提示符。更有可能的是需要的模块尚未导入。 - notjustme
以上链接不起作用,我无法找到等价物。 - S Raghav
也许这个可以帮到你:https://www.codeproject.com/Articles/18229/How-to-run-PowerShell-scripts-from-C - Afonso
@Afonso "糟糕!该页面无法找到。" - Scott Solmer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接