C#Runspace Powershell(交互式) [英] C# Runspace Powershell (Interactive)

查看:495
本文介绍了C#Runspace Powershell(交互式)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

由于主机程序或主机程序提示用户失败的命令 命令类型不支持用户交互.尝试一个主机程序 支持用户交互,例如Windows PowerShell控制台 或Windows PowerShell ISE,并从中删除与提示相关的命令 不支持用户交互的命令类型,例如Windows PowerShell工作流程.

我该怎么办?

当前的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;

解决方案

如果您需要运行使用非关键cmdlet(如write-host)的脚本,而该脚本需要完整的pshost,则可以添加"fake "功能对运行空间不起作用,或者不执行任何操作或登录到文本文件(或您想要的其他任何文件).

PS Code:

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

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

Write-Host $date;

exit;

If you need to run a script that uses non-critical cmdlets like write-host that require the presence of a fully-fledged pshost, you can add "fake" functions to the runspace that either do nothing or log to a text file (or anything else you want.) See my other answer here:

How can I execute scripts in a code created powershell shell that has Write-Host commands in it?

这篇关于C#Runspace Powershell(交互式)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆