2015年4月2日 星期四

Windows PowerShell "Pause"

Write-Host "Press any key to continue ..."
$x = $host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")


In this line we’re using PowerShell’s automatic variable $host (which is actually an instance of the .NET Framework class System.Management.Automation.Host) and the ReadKey method. (Which is actually a method of the RawUI property, which is a property of the UI property, which is a property of $host. And the leg bone’s connected to the knee bone, the knee bone’s connected to the ankle bone, the ….) The ReadKey method enables us to get information about the key that has just been pressed. Of course, in this case the only information we care about is the fact that a key has been pressed. Therefore, we pass ReadKey two parameters:

NoEcho. This prevents any information from appearing on screen when the user presses a key. If you leave out this parameter the pressed key will be echoed back to the screen.

IncludeKeyDown. This tells the script to continue as soon as a key has been pressed; that means the script will continue even if the user presses and holds a key down. If you’d prefer to wait until the user has released the key, then use this parameter instead: IncludeKeyUp.

There’s one more parameter that we can add to the ReadKey method: AllowCtrlC. In Windows PowerShell, pressing Ctrl+C typically causes the script to terminate. If you add the AllowCtrlC parameter to the ReadKey method, however, the user can choose to press Ctrl+C instead of pressing any other key. If they do that, the script will not terminate, but instead continue on as if the user had pressed any other key on the keyboard. (But only in conjunction with the ReadKey method. If the user presses Ctrl+C somewhere else the script will terminate.)

Reference:
Pausing a Script Until the User Presses a Key
How do you do a ‘Pause’ with PowerShell 2.0?
How to Properly Pause a PowerShell Script

沒有留言:

張貼留言