Powershell addscript 和 C# 调用不在命令行上显示结果

use*_*741 3 c# powershell

我有以下 powershell 脚本文件

C:\用户\桌面\script1.ps1

脚本的内容如下:

get-process
Run Code Online (Sandbox Code Playgroud)

我正在尝试创建一个 C# 控制台应用程序以在控制台上获取此脚本的输出。当我在 C# 外部执行脚本时,它运行良好,但当我在 C# 内部执行它时,它不会产生任何结果。我正在尝试使用 addscript 并调用。

C#代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Management.Automation;
using System.Collections.ObjectModel;


namespace InvokePowerShellScriptFrmCsharp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string script = @"C:\\Users\\Desktop\\script1.ps1";


            PowerShell shell = PowerShell.Create();

            shell.AddScript(script);
            //shell.AddCommand("get-process");

            shell.Invoke();
            //shell.AddScript(script).Invoke();

            Collection<PSObject> pSObjects = shell.Invoke();

            foreach (PSObject p in pSObjects)
            {
                Console.WriteLine(p.ToString());
            }
            Console.WriteLine("Press any key to continue");
            Console.ReadLine();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

当我执行上述命令时,控制台显示“按任意键继续”,但在此之前没有输出。

但如果我尝试下面的方法我会得到结果

shell.addcommand("get-process");
Run Code Online (Sandbox Code Playgroud)

我希望将来能够使用 addscript 来实现这一功能,因为如果 powershell 脚本中有多个命令,那么我需要能够从 C# 执行该脚本以获得所需的结果。

我已经尝试了很多链接来尝试研究,但似乎没有让它发挥作用。

https://blogs.msdn.microsoft.com/kebab/2014/04/28/executing-powershell-scripts-from-c/

https://www.reddit.com/r/csharp/comments/692mb1/running_powershell_scripts_in_c/

有人可以告诉我哪里可能出错吗?

box*_*dog 6

尝试首先加载脚本内容,然后将其传递给AddScript方法:

string script = File.ReadAllText(@"C:\Scripts\script1.ps1");
Run Code Online (Sandbox Code Playgroud)