有没有可能从作为进程调用的PowerShell脚本中获取输入?

3
我们有一个PowerShell脚本文件(.ps1),它要求用户从PowerShell控制台提供输入,并将其作为参数传递给另一个PowerShell脚本文件(.ps1),该脚本文件还要求用户提供输入。为了获取输入,我们使用"Read-Host"。
以下是代码片段,在执行下面的代码时,test2脚本不会要求输入,进程会停止/暂停。
有人能帮我如何实现这个用例吗?

Code 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 

2
有没有特别的原因你要生成一个新的进程?为什么不直接从第一个脚本调用第二个脚本呢?例如:$new_ip = Read-Host -Prompt "输入IP"; .\script2.ps1 -ServerIP $new_ip - undefined
为什么要使用Read-Host?使用强制参数不是更好吗? - undefined
你对第二个脚本有控制权吗?如果你有一种编程方式来回答第二个脚本的Read-Host提示,你会使用什么值? - undefined
嗨,Jessen,我们希望用户能够从 Powershell 控制台执行第二个脚本并提供输入,以便用户可以单独执行 Test1.ps1 和 Test2。 - undefined
嗨mklement0,回答你的第一个问题->是的,我们想要控制第二个脚本。至于第二个问题,我们不知道该如何做到。 - undefined
1个回答

2

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

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

不确定这是否是正确的答案


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接