代码之家  ›  专栏  ›  技术社区  ›  asgallant

如何使Powershell脚本响应用户输入提示?

  •  7
  • asgallant  · 技术社区  · 7 年前

    我有一个Powershell脚本,需要执行一个命令行可执行文件,提示用户输入(没有命令行参数)。类似这样:

    # promptsForInput.ps1
    $someInput = Read-Host "Gimme some input"
    # do something with $someInput
    

    # myScript.ps1
    .\promptsForInput.ps1
    

    在运行时,我会被提示输入一些内容:

    > .\myScript.ps1
    Gimme some input:
    

    我需要能够在没有用户干预的情况下填写输入请求。什么时候 promptsForInput.ps1 提示用户输入,我需要 myScript.ps1 输入所需的值并继续执行脚本。

    关于SO的类似问题要么有特定于特定exe的答案,要么没有帮助:

    2 回复  |  直到 7 年前
        1
  •  6
  •   Bill_Stewart    7 年前
    1. 不要使用 $input 变量的名称,因为它是PowerShell中的自动变量(请参阅 help about_Automatic_Variables

    2. 确定可执行文件是否可以接受命令行参数,而不是停止或提示输入。如果可用,这显然是首选。

    3. 您是否可以告诉PowerShell自动将输入发送到任意可执行文件取决于该可执行文件的设计。如果可执行文件允许您向其发送标准输入,则可以运行以下操作

      "test" | myexecutable.exe
      

      test 以及返回作为可执行文件的标准输入。如果可执行文件接受标准输入,那么这将起作用。

      如果可执行文件 使用标准输入,然后您必须执行不同的操作,例如向窗口发送击键。我认为发送击键是最后的手段,也是不利于自动化的脆弱解决方案。

        2
  •  0
  •   Vijred    3 年前

    下面是我用来运行批处理文件并提供输入的示例

    [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
    Start-Process -FilePath C:\myexecbatchfile.bat
    
    # Wait the application start for 2 sec 
    Start-Sleep -m 2000
     
    # Send keys
    [System.Windows.Forms.SendKeys]::SendWait("input1")
    [System.Windows.Forms.SendKeys]::SendWait("{ENTER}")
    Start-Sleep -m 3000
    
    [System.Windows.Forms.SendKeys]::SendWait("input2")
    [System.Windows.Forms.SendKeys]::SendWait("{ENTER}")