【问题标题】:powershell Import module not working properlypowershell导入模块无法正常工作
【发布时间】:2015-12-21 11:06:32
【问题描述】:

如何在C#中验证模块(Import module)命令是否成功导入模块?我有自己的自定义 powershell,它是在 Windows powershell 中导入的。我编写了 C# 代码,它将我的自定义 powershell 导入到 windows powershell 中,当我尝试从代码执行自定义 powershell 命令时,它没有返回任何结果,而当我执行来自 windows powershell 的相同命令(通过导入模块并编写自定义 powershell 命令)它正在工作。我正在使用以下代码

InitialSessionState initial = InitialSessionState.CreateDefault();
initial.ImportPSModule(new string[] { "ABCD" });
Runspace runspace = RunspaceFactory.CreateRunspace(initial);
initial.ThrowOnRunspaceOpenError = true;
runspace.Open();
RunspaceInvoke runSpaceInvoker = new  RunspaceInvoke(runspace); 
runSpaceInvoker.Invoke("Set-ExecutionPolicy Unrestricted");
PowerShell ps = PowerShell.Create();
ps.Runspace = runspace;      
string script = System.IO.File.ReadAllText(@"D:\Export-Pipeline-Script.txt");
ps.AddScript(script);
ps.Invoke();
ps.Commands.Clear();
ps.AddCommand("Test2");
Collection<PSObject> results1 = ps.Invoke();
foreach (PSObject outputItem in results1)
{
    if (outputItem != null)
    {
        Console.WriteLine(outputItem.ToString());
    }
}  

在 AddCommand 中,Test2 是一个函数,我在其中编写了自定义 powershell 命令。在上面的代码 results1 中,count 总是写为“0”,而当我将自定义 powershell 命令更改为像 Get-Process 这样的 windows powershell 命令时,它可以工作。

【问题讨论】:

    标签: c# powershell powershell-3.0


    【解决方案1】:

    这是一个对我有用的例子。我创建了一个 PS 模块和一个自定义 PS 脚本,并在您的 C# 代码中使用了它们。这可能会为您提供一些关于如何使您的工作发挥作用的线索。

    C:\Temp\PowerShell.Module.psm1

    这是自定义的强力地狱。 C:\Temp\PS\GetProc.ps1

    使用此代码:

    InitialSessionState initial = InitialSessionState.CreateDefault();
    initial.ImportPSModule(new string[] { @"C:\Temp\PowerShell.Module.psm1" });
    Runspace runspace = RunspaceFactory.CreateRunspace(initial);
    initial.ThrowOnRunspaceOpenError = true;
    runspace.Open();
    RunspaceInvoke runSpaceInvoker = new  RunspaceInvoke(runspace); 
    runSpaceInvoker.Invoke("Set-ExecutionPolicy Unrestricted");
    PowerShell ps = PowerShell.Create();
    ps.Runspace = runspace;      
    string script = System.IO.File.ReadAllText(@"C:\Temp\Export-Pipeline-Script.txt");
    ps.AddScript(script);
    ps.Invoke();
    ps.Commands.Clear();
    ps.AddCommand("GetProc");
    Collection<PSObject> results1 = ps.Invoke();
    foreach (PSObject outputItem in results1)
    {
        if (outputItem != null)
        {
            Console.WriteLine(outputItem.ToString());
        }
    } 
    

    结果:

    【讨论】:

    • 您是否只是为了避免懒惰复制而使用代码截图?文字总是更好。
    • 我在自己的示例中使用了屏幕截图,因为 OP 没有提供有关他的 PS 代码的足够信息。所以我打算我的例子只是一个说明性的替代方案。这也使 OP 也避免了懒惰的复制。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-06
    • 2018-02-14
    • 2013-06-10
    相关资源
    最近更新 更多