是否可以从称为进程的 powershell 脚本中获取输入?

问题描述

我们有一个 PowerShell 脚本文件 (.ps1),它要求用户从 PowerShell 控制台提供输入,并将作为参数传递给另一个 PowerShell 脚本文件 (.ps1),该脚本文件也要求用户输入。为了获取输入,我们使用“Read-Host

下面是代码片段,在执行下面的代码时,它不会询问 test2 脚本的输入,并且进程卡住/暂停。

有人可以帮助我如何实现这个用例吗?

代码 Test1.ps1

[System.String] $ScriptPath = Split-Path -Parent $MyInvocation.MyCommand.Path

     $new_ip = Read-Host -Prompt "Enter IP"
    if([string]::IsNullOrWhiteSpace($new_ip))
    {
     $pinfo = New-Object System.Diagnostics.processstartinfo
     $pinfo.FileName = "PowerShell.exe"
     $pinfo.RedirectStandardError = $true
     $pinfo.RedirectStandardOutput = $true
     $pinfo.UseShellExecute = $false
     $pinfo.WindowStyle = 'Hidden'
     $pinfo.CreateNowindow = $True
     $pinfo.Arguments = "-file `"$ScriptPath\Test2.ps1`" -ServerIP `"$new_ip`""
     $p = New-Object System.Diagnostics.Process
     $p.StartInfo = $pinfo
     $p.Start() | Out-Null
     $stderr = $p.StandardError.ReadToEnd()
     $stdout = $p.StandardOutput.ReadToEnd()
     $p.WaitForExit()
    
        
        if (![string]::IsNullOrEmpty($stderr))
         {
            Write-Warning "stderr: $stderr"
         }
         if($p.ExitCode -ne 0)
         {
            $isValidIP = $false
            Write-Warning " Failed,Check above message"
          }
          else
          {
             Write-Host $stdout
             $isValidIP = $true
             Write-Host "Configured successfully"
          }
    }
    
    
    **Test2.ps1**
    
    Param([String]$ServerIP = $null
        )
    
    Write-Host "Server IP:"$ServerIP
    
    $sqlServerIP = (Read-Host -prompt "Enter sql Server IP address (Default : localhost) ")
    Write-Host "Server IP:"$sqlServerIP 

解决方法

我不确定我们是否可以将后台正在运行的进程的用户输入提示重定向到主窗口。但是我们可以使用

将输入发送到等待用户输入的进程
$p.StandardInput.WriteLine("yourIP"); 

不确定这是否是合适的答案