Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/295.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 我需要从C和执行powershell脚本;输入;当程序提示我时的响应_C#_Windows_Powershell_Visual Studio 2015_Command Prompt - Fatal编程技术网

C# 我需要从C和执行powershell脚本;输入;当程序提示我时的响应

C# 我需要从C和执行powershell脚本;输入;当程序提示我时的响应,c#,windows,powershell,visual-studio-2015,command-prompt,C#,Windows,Powershell,Visual Studio 2015,Command Prompt,编辑:我改变了很多问题 我一直在努力从C#执行powershell命令,并在出现提示时向其发送用户输入 这是我的代码> 我想听到提示,并在程序要求时输入一些数据 例如,如果我想执行一个命令ftp,然后当它提示我输入时,我想键入quit。我可以用Powershell做这个吗 private string RunScript(List<string> scriptText) { StringBuilder stringBuilder = new Strin

编辑:我改变了很多问题

我一直在努力从C#执行powershell命令,并在出现提示时向其发送用户输入

这是我的代码>

我想听到提示,并在程序要求时输入一些数据

例如,如果我想执行一个命令
ftp
,然后当它提示我输入时,我想键入
quit
。我可以用Powershell做这个吗

    private string RunScript(List<string> scriptText)
    {
        StringBuilder stringBuilder = new StringBuilder();
        Runspace runspace = RunspaceFactory.CreateRunspace();
        runspace.Open();
        Pipeline pipeline = runspace.CreatePipeline();
        pipeline.Commands.Add("Out-String");
        foreach (string str in scriptText)
        {
            Command cmd = new Command(str, false); ;
            pipeline.Commands.Add(cmd);
        }
        pipeline.InvokeAsync();

        while (!pipeline.Output.EndOfPipeline)
        {
            stringBuilder.AppendLine(pipeline.Output.ToString());
        }

        runspace.Close();
        return stringBuilder.ToString();
    }
私有字符串运行脚本(列表脚本文本)
{
StringBuilder StringBuilder=新的StringBuilder();
Runspace Runspace=RunspaceFactory.CreateRunspace();
Open();
Pipeline Pipeline=runspace.CreatePipeline();
pipeline.Commands.Add(“输出字符串”);
foreach(脚本文本中的字符串str)
{
Command cmd=新命令(str,false);
管道命令.添加(cmd);
}
pipeline.InvokeAsync();
而(!pipeline.Output.EndOfPipeline)
{
AppendLine(pipeline.Output.ToString());
}
runspace.Close();
返回stringBuilder.ToString();
}

不清楚您想要实现什么,但是:

  • 程序在第一个错误时退出,因此不调用第二个命令
  • 您的代码抛出了一个错误,因为未找到
    Test1
    ,我假设也找不到
    Test2
  • 脚本或命令必须存在
例如:

PowerShell ps = PowerShell.Create();
ps.AddScript(“D:\PSScripts\MyScript.ps1”).Invoke();

更多信息请参见

如果第一个命令是cmdlet、函数、脚本文件或可操作程序,即不会导致错误,会发生什么情况?
dir | ipconfig
:输出
dir
转到
ipconfig
。如果前面的问题得到回答,则应将其标记为已解决。如果你有一个新问题,那么你需要问一个新问题。您不应该完全更改您的问题。您可以在PowerShell中轻松完成此操作。但是为什么你的问题是c#代码呢?在上面编辑过,我用dir和ipconfig替换了tets1和test2,但它仍然只显示第二个命令的输出。很抱歉,我重新安排了很多问题,我需要添加输入,而不是第二个脚本