【问题标题】:Import PowerShell Module from C# Failing从 C# 导入 PowerShell 模块失败
【发布时间】:2016-11-12 12:38:16
【问题描述】:

我见过很多解决方案,但没有一个能解决我的问题。 我正在尝试将一个名为“DSInternals”的自定义 PowerShell 模块导入到我的 C# DLL。

https://github.com/MichaelGrafnetter/DSInternals

我的代码中的一切看起来都很好,但是当我尝试获取可用模块时,它没有加载。

流响应

“Get-ADReplAccount”一词未被识别为 cmdlet、函数、脚本文件或可运行程序的名称。检查名称的拼写,或者如果包含路径,请验证路径是否正确并重试。

这段代码哪里出错了?

InitialSessionState init = InitialSessionState.CreateDefault();
init.ImportPSModule(new string[] { @"D:\\DSInternals\\dsinternals.psd1" }); //location of the module files
Runspace runspace = RunspaceFactory.CreateRunspace(init);
runspace.Open();
PowerShell ps = PowerShell.Create();
ps.Runspace = runspace;
ps.Commands.AddCommand("Get-ADReplAccount"); //this command is un-recognized

foreach (PSObject result in ps.Invoke())
{
    Console.WriteLine(result); //this always returns null
}

【问题讨论】:

  • 此命令无法识别 你怎么知道的?有没有抛出异常? ps.Streams.Error 有错误吗?
  • 流响应“‘Get-ADReplAccount’一词未被识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,或者如果路径已包含,请验证路径是否正确,然后重试。”。此 cmdlet 包含在 DSInternals 模块中
  • 将此添加到您的代码中:init.ThrowOnRunspaceOpenError=true;.
  • 非常感谢@PetSerAl 正是我重回正轨所需要的。

标签: c# powershell dll import-module


【解决方案1】:

问题在于内置模块的 .NET 框架版本。 将使用更高版本的 .NET 框架构建的模块添加到 C# 类将不起作用。 该模块是在 4.5.1 中构建的,我正在使用版本 2,添加了

init.ThrowOnRunspaceOpenError=true;

帮助找出错误的原因。

这是我的最终代码

        InitialSessionState init = InitialSessionState.CreateDefault();
        init.ImportPSModule(new string[] { @"D:\\DSInternals\\dsinternals.psd1" }); //location of the module files
        init.ThrowOnRunspaceOpenError = true;
        Runspace runspace = RunspaceFactory.CreateRunspace(init);
        runspace.Open();
        var script =
            "Get-ADReplAccount -SamAccountName peter -Domain BLABLA -Server dc.BLABLA.co.za -Credential $cred -Protocol TCP"; //my powershell script

        _powershell = PowerShell.Create().AddScript(script);
        _powershell.Runspace = runspace;

        var results = _powershell.Invoke();
        foreach (var errorRecord in _powershell.Streams.Progress)
            Console.WriteLine(errorRecord);
        foreach (var errorRecord in _powershell.Streams.Debug)
            Console.WriteLine(errorRecord);
        foreach (var errorRecord in _powershell.Streams.Error)
            Console.WriteLine(errorRecord);
        foreach (var errorRecord in _powershell.Streams.Warning)
            Console.WriteLine(errorRecord);

        var stringBuilder = new StringBuilder();
        foreach (var obj in results)
        {
            stringBuilder.AppendLine(obj.ToString());
        }

        return stringBuilder.ToString();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-28
    • 1970-01-01
    • 2020-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多