1
$inputYN = Read-Host "(defaults to y in 10 sec) [y/n] ";

If user doesn't provide any input in 10 second then default $inputYN should go to "Yes" and move forward to next task.

Davor Josipovic
  • 5,296
  • 1
  • 39
  • 57
Krish
  • 439
  • 1
  • 5
  • 5
  • 2
    Part of the answer is here: http://stackoverflow.com/questions/150161/waiting-for-user-input-with-a-timeout – Davor Josipovic Jun 06 '13 at 14:34
  • I am new to powershell and try to do this. If you have any code for this task, please post it. Thanks in advance. – Krish Jun 06 '13 at 14:43

1 Answers1

7

Your question intrigued me. I'm not sure how well this will work, but I tested it a couple of times and got the correct keys back. Doesn't work too well if you try to enter capital letters. There has to be a better way than this, though. You can always check with other forums like PowerShell.com or PowerShell.org to get a different crowd.

function Get-Answer {
    $counter = 0
    while($counter++ -lt 100){
        if($Host.UI.RawUI.KeyAvailable){
            #You could check to see if it was the "Shift Key or another"
            $key = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyUp")
            break
        }
        else{
            Start-Sleep -Milliseconds 100
            $key = $false
        }
    }
    return ($key)
}

Write-Host 'Enter y/n'
$answers = Get-Answer
if($answers -eq $false -or ($answers.Character -eq 'y')){
    "Yes is default"
}
elseif($answers.Character -eq 'n'){
    "NO!!!!"
}
else{
    "Invalid Key $($answers.Character): `"YES`" is being used now."
}
E.V.I.L.
  • 2,120
  • 13
  • 14