回答power shell 自动调用exe程序并根据输出自动交互的问题


 

## Prepare to invoke the process
$processStartInfo = New-Object System.Diagnostics.ProcessStartInfo
$processStartInfo.FileName = (Get-Command ".\a.exe").Definition
$processStartInfo.WorkingDirectory = (Get-Location).Path
#Arguments为程序参数
$processStartInfo.Arguments = " -c -d -e"
$processStartInfo.UseShellExecute = $false
## Always redirect the input and output of the process.
$processStartInfo.RedirectStandardOutput = $true
#RedirectStandardInput = $true实现了输入流的重定向,运行程序以后无法从键盘获取输入
$processStartInfo.RedirectStandardInput = $true
$process = [System.Diagnostics.Process]::Start($processStartInfo)
#default reply "y"
$Reply = "y"
do
{
    ## get the StandardOutput and write to host
    $LineRead = $process.StandardOutput.ReadLine()
    if($LineRead -eq $null) {break}
    else
    {
        write-host $LineRead.toString()
    }

    #If queation a
    if($LineRead.toString() -eq "queation a?")
    {
        $Reply = "n"
    }
    if($LineRead.toString() -eq "Enter your Option : ")
    {
        #写入输入流方案1???????????????????????????????????????????????
        $process.StandardInput.BaseStream.Write($Reply, 0, $Reply.Count)
        $process.StandardInput.Close()

        #写入输入流方案2???????????????????????????????????????????????
        $input | % { $process.StandardInput.WriteLine($_) }
        $process.StandardInput.Close()
    }
} while($true)

我今天在论坛里找到了一些英文的资料看了一下,发现一个不错的方法,我按照那种方法又写了一段程序,把输出流,输入流全部重定向,发现还是还是上述的问题,可以抓取到输出流,但是怎样自动写入输入流呢?程序如下,疑难点就在两串打问号的地方。输入流的重定向已经完成了,但是无法把信息写入输入流,到底是为什么?