gpt4 book ai didi

c# - 在 C# 中执行 powershell 脚本

转载 作者:行者123 更新时间:2023-11-30 17:33:29 27 4
gpt4 key购买 nike

下面是我用来尝试执行我的 powershell 脚本的脚本,但每当我运行它时,我只会看到一个空白的命令窗口。

C#代码

static void Main(string[] args)
{
string text = System.IO.File.ReadAllText(@"C:\Program Files (x86)\Backup Reporter\Required\edit_website.ps1");

using (PowerShell PowerShellInstance = PowerShell.Create())
{
// use "AddScript" to add the contents of a script file to the end of the execution pipeline.
// use "AddCommand" to add individual commands/cmdlets to the end of the execution pipeline.
PowerShellInstance.AddScript(text);

Collection<PSObject> PSOutput = PowerShellInstance.Invoke();
foreach (PSObject outputItem in PSOutput)
{
// if null object was dumped to the pipeline during the script then a null
// object may be present here. check for null to prevent potential NRE.
if (outputItem != null)
{
Console.WriteLine(outputItem.BaseObject.ToString() + "\n");
}
}
if (PowerShellInstance.Streams.Error.Count > 0)
{
Console.Write("Error");
}
Console.ReadKey();
}
}

Powershell 脚本

 $text = "test test test"

我只想将测试输出到命令窗口。

最佳答案

您可以使用 Write-Output 而不是 Write-Host。从 winform 应用程序调用时它对我有用。

关于c# - 在 C# 中执行 powershell 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43855697/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com