C#调用Powershell脚本时出现问题

时间:2018-12-26 06:25:58

标签: c# powershell .net-core-2.1

我为C#调用Powershell脚本创建了一个控制台应用程序(基于.net core 2.1),但是我得到了NULL值。有人可以告诉我哪里/哪一步/哪一步错了或丢失了吗?

以下是异常详细信息:

Exception

private static void Main(string[] args)
    {    //.net core 2.1
        string ScriptsText = @"C:\temp\getEvent.ps1";

        Runspace runspace = RunspaceFactory.CreateRunspace();
        runspace.Open();

        PowerShell shell = PowerShell.Create();
        shell.AddScript(ScriptsText);
        shell.Runspace = runspace;

        Collection<PSObject> psObjects = shell.Invoke();
        //format the psobjects to string object
        StringBuilder stringBuilder = new StringBuilder();
        foreach (PSObject obj in psObjects)
        {
            stringBuilder.AppendLine(obj.ToString());
        }
        runspace.Close();
        Console.WriteLine(stringBuilder.ToString());
    }

变量:ps对象在调用后应包含结果,但现在显示空值

附加了powershell脚本内容: C:\ temp \ getEvent.ps1:

$ result = Get-EventLog -LogName系统-最新5; 返回$ result

准备了用于测试目的的不同Powershell脚本

  1. part cmdlet可以正常工作(请参见下面的屏幕截图)
  2. part cmdlet由C#调用时返回null(请参见下面的屏幕截图)

Same C# code invoke powershell script, return null

Same C# code invoke powershell script, return null

Same C# code invoke powershell script, return value

Same C# code invoke powershell script, return value

0 个答案:

没有答案