Powershell等待按键

时间:2013-12-30 18:13:47

标签: powershell wait keypress

我想在自动输入“Hello this is a test”后暂停此脚本,按 enter 键后,它应等待 F2 键按下。  怎么办?

function wait {
param([int]$stop = 3)
Start-Sleep -seconds $stop
}


[void] [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.VisualBasic")
& "$env:Windir\notepad.exe"
$a = Get-Process | Where-Object {$_.Name -eq "Notepad"}
wait

[System.Windows.Forms.SendKeys]::SendWait("Hello this is a test")
[System.Windows.Forms.SendKeys]::SendWait("{ENTER}")
wait

# here I want something like wait for F2 key to be pressed
# after the F2 key was pressed I want the script to continue

[System.Windows.Forms.SendKeys]::SendWait("This is After the key was pressed")
[System.Windows.Forms.SendKeys]::SendWait("{ENTER}")

exit

2 个答案:

答案 0 :(得分:3)

以下是您的脚本的修改版本,可以实现您的目标。请记住,这在PowerShell集成脚本编辑器(ISE)中不起作用。

$Wait = 3;

[void] [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.VisualBasic")
& "$env:Windir\notepad.exe"
$a = Get-Process | Where-Object {$_.Name -eq "Notepad"}
Start-Sleep -Seconds $Wait;

[System.Windows.Forms.SendKeys]::SendWait("Hello this is a test")
[System.Windows.Forms.SendKeys]::SendWait("{ENTER}")
Start-Sleep -Seconds $Wait;

while ([System.Console]::ReadKey().Key -ne [System.ConsoleKey]::F2) { };

[System.Windows.Forms.SendKeys]::SendWait("This is After the key was pressed")
[System.Windows.Forms.SendKeys]::SendWait("{ENTER}")

exit

答案 1 :(得分:0)

以下内容将循环,直到按下F2,并提示用户。

do{ echo "Press F2";$x = [System.Console]::ReadKey() } while( $x.Key -ne "F2" )