我有以下 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 来实现这一功能,因为如果 …