首页 文章

powershell导入模块无法正常工作

提问于
浏览
-1

如何验证模块(导入模块)命令是否在C#中成功导入模块?我有自己的自定义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总是写为“0”,而当我将自定义powershell命令更改为像windows-powershell命令这样的Get-Process时,它可以工作 .

1 回答

  • 0

    这是一个适合我的例子 . 我创建了一个PS模块和一个自定义PS脚本,并在您的C#代码中使用它们 . 这可能会为您提供一些线索,让您了解如何让您的工作 .

    C:\Temp\PowerShell.Module.psm1
    enter image description here

    这是自定义的powerhell . C:\Temp\PS\GetProc.ps1

    enter image description here

    使用此代码:

    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());
        }
    }
    

    结果:

    enter image description here

相关问题