C# Runspace Powershell(交互式)

标签 c# powershell runspace

我正在尝试使用 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/

相关文章:

c# - Powershell 如何知道在哪里可以找到要导入的模块?

powershell - 带有运行空间池的 SessionStateProxy 变量

c# - 在窗体关闭时关闭 SQL 连接 (C#)

mysql - 使用 Force 在 Windows 上导入大型 MySQL .sql 文件

powershell - 通过 Graph 更新 AzureAD/O365 UPN

azure - 如何知道PowerShell中是否存在特定字符串?

带 RunspacePool 的 C# PowerShell - 如何导入 Exchange Cmdlet,如 Get-Mailbox?

c# - 创建/更新/删除分层数据的正确方法

c# - 如何使用用户控件后台代码中存在的事件处理程序以编程方式打开和关闭 bottomappbar?

c# - 动态创建/加载用户控件只能工作一次!