gpt4 book ai didi

C# Runspace Powershell(交互式)

转载 作者:太空狗 更新时间:2023-10-29 22:22:23 24 4
gpt4 key购买 nike

我正在尝试使用 C# 在运行空间中执行带有参数的 Powershell 文件。不幸的是我得到以下输出:

A command that prompts the user failed because the host program or the command type does not support user interaction. Try a host program that supports user interaction, such as the Windows PowerShell Console or Windows PowerShell ISE, and remove prompt-related commands from command types that do not support user interaction, such as Windows PowerShell workflows.

我能做什么?

当前的 C# 代码。这需要执行将在 PS 文件中的命令,并且需要返回一个 json 字符串。

public string ExecuteCommandDirect(int psId, string psMaster, string psFile)
{
String FullPsFilePath = @"C:\CloudPS\" + psFile + ".ps1";

String PsParameters = FullPsFilePath + " -psId " + psId + " -psMaster " + psMaster + " -NonInteractive";

// Create Powershell Runspace
Runspace runspace = RunspaceFactory.CreateRunspace();

runspace.Open();

// Create pipeline and add commands
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript(PsParameters);

// Execute Script
Collection<PSObject> results = new Collection<PSObject>();
try
{
results = pipeline.Invoke();
}
catch (Exception ex)
{
results.Add(new PSObject((object)ex.Message));
}

// Close runspace
runspace.Close();

//Script results to string
StringBuilder stringBuilder = new StringBuilder();
foreach (PSObject obj in results)
{
Debug.WriteLine(obj);
stringBuilder.AppendLine(obj.ToString());
}

return stringBuilder.ToString();

}

PS代码:

param([int]$psId = 0, [string]$psMaster = 'localhost');

$date = Get-Date -Format 'h:m:s' | ConvertTo-Json;

Write-Host $date;

exit;

最佳答案

使用Write-Output代替Write-Host

关于C# Runspace Powershell(交互式),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25963566/

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