我有下面的 powershell 脚本文件
C:\user\deskptop\script1.ps1
脚本内容如下:
get-process
我正在尝试创建一个 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();
}
}
}
当我执行上面的命令时,我得到控制台“按任意键继续”,但在此之前没有输出。
但如果我只是尝试下面的方法,我会得到结果
shell.addcommand("get-process");
如果 powershell 脚本中有多个命令,我想在将来使用 addscript 来实现这一点,然后我需要能够从 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/
有人可以让我知道我可能哪里出错了。
最佳答案
首先尝试加载脚本内容,然后将其传递给 AddScript
方法:
string script = File.ReadAllText(@"C:\Scripts\script1.ps1");
关于c# - Powershell 添加脚本并从 C# 调用不在命令行上显示结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52992968/