【问题标题】:Powershell script waiting for user input and wont exitPowershell脚本等待用户输入并且不会退出
【发布时间】:2021-08-06 01:55:32
【问题描述】:

我正在尝试以静默方式运行脚本,它运行良好,但运行后会显示 成功:0 按“Enter”继续

如何检查是否成功,然后发送回车键..

请注意,我是通过下面的启动进程命令运行它,但由于它正在等待用户按 Enter,所以它永远不会退出:

Start-Process -Wait -FilePath "C:\windows\temp\abc.exe" -ArgumentList '/S','/v','/qn' -passthru

【问题讨论】:

    标签: powershell


    【解决方案1】:

    最好的办法是检查您的可执行文件是否支持在末尾跳过提示符的命令行参数(选项)

    如果没有,您可以尝试以下方法,但请注意,与所有通过模拟用户交互控制应用程序的尝试一样,该解决方案既笨拙又脆弱强>:

    # Comment this out to hide the verbose messages.
    $VerbosePreference = 'Continue'
    
    # Load helper assemblies.
    Add-Type -ErrorAction Stop -AssemblyName Microsoft.VisualBasic, System.Windows.Forms
    
    # Launch the external program.
    # In this simple example, cmd.exe is invoked with its internal pause
    # command, which waits for a keystroke to continue.
    Write-Verbose 'Launching the external program asynchronously...'
    # IMPORTANT: Do NOT use -Wait, as that will block execution
    #            indefinitely, and prevent you from sending the Enter keystroke.
    $process = Start-Process -PassThru cmd '/c pause'
    
    Write-Verbose 'Sleeping for as long as execution is expected to last at a minimum...'
    Start-Sleep 5  # Adjust this as needed.
    
    Write-Verbose 'Sending ENTER keystrokes until the window closes...'
    while (-not $process.HasExited) {
      # To be safe, activate the external program's window. If that fails, it must be closed already.
      try { [Microsoft.VisualBasic.Interaction]::AppActivate($process.Id) } catch { break }
      # Send the keystroke.
      [System.Windows.Forms.SendKeys]::SendWait('{Enter}')
      Start-Sleep -Milliseconds 200  # Sleep a little between attempts.
    }
    
    Write-Verbose 'The external program''s window is now closed.'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多