문제

검색했지만 분명히 내 Google Foo는 약합니다. 필요한 것은 콘솔에서 사용자 입력을 자랑하고 일정 기간 후에 요청 시간을 보내고 입력이 들어오지 않으면 스크립트를 계속 실행할 수있는 방법입니다. 알 수 있듯이 Read-Host는 이것을 제공하지 않습니다. 기능. $ host.ui.promptforchoice ()도 $ host.ui.rawui.readkey ()도 마찬가지입니다. 포인터에 미리 감사드립니다.

편집 : 답변을 찾은 Lars Truijens에게 감사드립니다. 나는 그가 지적한 코드를 가져 와서 그것을 함수로 캡슐화했다. 내가 구현 한 방식은 사용자가 키를 눌렀을 때와 스크립트 실행이 계속 될 때까지 최대 1 초의 지연이있을 수 있음을 의미합니다.

function Pause-Host
{
    param(
            $Delay = 1
         )
    $counter = 0;
    While(!$host.UI.RawUI.KeyAvailable -and ($counter++ -lt $Delay))
    {
        [Threading.Thread]::Sleep(1000)
    }
}
도움이 되었습니까?

해결책

뭔가를 찾았습니다 여기:

$counter = 0
while(!$Host.UI.RawUI.KeyAvailable -and ($counter++ -lt 600))
{
      [Threading.Thread]::Sleep( 1000 )
}

다른 팁

지금은 꽤 오래되었지만 동일한 KeyAvailable 방법을 기반으로 어떻게 해결했는지는 다음과 같습니다.

https://gist.github.com/nathanchere/704920a43f06f4f0d2

x 초 동안 기다립니다 . 최대 대기 시간까지 경과하는 각 초에 대해. 키를 누르면 반환됩니다 $true, 그렇지 않으면 $false.

Function TimedPrompt($prompt,$secondsToWait){   
    Write-Host -NoNewline $prompt
    $secondsCounter = 0
    $subCounter = 0
    While ( (!$host.ui.rawui.KeyAvailable) -and ($count -lt $secondsToWait) ){
        start-sleep -m 10
        $subCounter = $subCounter + 10
        if($subCounter -eq 1000)
        {
            $secondsCounter++
            $subCounter = 0
            Write-Host -NoNewline "."
        }       
        If ($secondsCounter -eq $secondsToWait) { 
            Write-Host "`r`n"
            return $false;
        }
    }
    Write-Host "`r`n"
    return $true;
}

그리고 사용하려면 :

$val = TimedPrompt "Press key to cancel restore; will begin in 3 seconds" 3
Write-Host $val

사전 정의 된 키 프레스에서 PowerShell 스크립트를 종료하기위한 추가 제약 조건이있는 현대 시대 솔루션을 찾고있는 사람들의 경우 다음 솔루션이 도움이 될 수 있습니다.

Write-Host ("PowerShell Script to run a loop and exit on pressing 'q'!")
$count=0
$sleepTimer=500 #in milliseconds
$QuitKey=81 #Character code for 'q' key.
while($count -le 100)
{
    if($host.UI.RawUI.KeyAvailable) {
        $key = $host.ui.RawUI.ReadKey("NoEcho,IncludeKeyUp")
        if($key.VirtualKeyCode -eq $QuitKey) {
            #For Key Combination: eg., press 'LeftCtrl + q' to quit.
            #Use condition: (($key.VirtualKeyCode -eq $Qkey) -and ($key.ControlKeyState -match "LeftCtrlPressed"))
            Write-Host -ForegroundColor Yellow ("'q' is pressed! Stopping the script now.")
            break
        }
    }
    #Do your operations
    $count++
    Write-Host ("Count Incremented to - {0}" -f $count)
    Write-Host ("Press 'q' to stop the script!")
    Start-Sleep -m $sleepTimer
}
Write-Host -ForegroundColor Green ("The script has stopped.")

샘플 스크립트 출력 :enter image description here

나타내다 마이크로 소프트 문서 더 많은 조합을 처리하기위한 주요 상태에서.

크레딧 : 테크넷 링크

다음은 다음과 같이 받아들이는 KeyStroke 유틸리티 기능입니다.

  • 유효성 검사 문자 세트 (1- 문자 Regex).
  • 선택적 메시지
  • 선택적 시간 초과는 초입니다

일치하는 키 스트로크 만 화면에 반영됩니다.

용법:

$key = GetKeyPress '[ynq]' "Run step X ([y]/n/q)?" 5

if ($key -eq $null)
{
    Write-Host "No key was pressed.";
}
else
{
    Write-Host "The key was '$($key)'."
}

구현:

Function GetKeyPress([string]$regexPattern='[ynq]', [string]$message=$null, [int]$timeOutSeconds=0)
{
    $key = $null

    $Host.UI.RawUI.FlushInputBuffer() 

    if (![string]::IsNullOrEmpty($message))
    {
        Write-Host -NoNewLine $message
    }

    $counter = $timeOutSeconds * 1000 / 250
    while($key -eq $null -and ($timeOutSeconds -eq 0 -or $counter-- -gt 0))
    {
        if (($timeOutSeconds -eq 0) -or $Host.UI.RawUI.KeyAvailable)
        {                       
            $key_ = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown,IncludeKeyUp")
            if ($key_.KeyDown -and $key_.Character -match $regexPattern)
            {
                $key = $key_                    
            }
        }
        else
        {
            Start-Sleep -m 250  # Milliseconds
        }
    }                       

    if (-not ($key -eq $null))
    {
        Write-Host -NoNewLine "$($key.Character)" 
    }

    if (![string]::IsNullOrEmpty($message))
    {
        Write-Host "" # newline
    }       

    return $(if ($key -eq $null) {$null} else {$key.Character})
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top