【问题标题】:Running PowerShell cmdlets in C#在 C# 中运行 PowerShell cmdlet
【发布时间】:2018-12-07 09:11:01
【问题描述】:

我需要在 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 中运行命令时它仍然有效。

【问题讨论】:

  • 这个错误意味着很可能模块没有被导入。请检查this answer 是否对您有帮助。

标签: c# visual-studio powershell office365 cmdlets


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • You are executing a command prompt, not a powershell command 嗯?我会说提到的异常肯定来自 PowerShell 而不是命令提示符。很有可能还没有导入所需的模块。
    • 以上链接失效,我找不到对应的
    • 也许这个对你有帮助:codeproject.com/Articles/18229/…
    • @Afonso “糟糕!找不到该页面。”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 2021-03-03
    • 1970-01-01
    • 2013-06-08
    • 1970-01-01
    • 1970-01-01
    • 2018-12-14
    相关资源
    最近更新 更多