我已经搜查了但显然我的谷歌foo是微弱的。我需要的是一种方法来提示用户输入在控制台有请求的时间在一段时间之后并继续执行该脚本,如果没有输入进来。因为附近我可以告诉读主不提供这种功能。也不$host.用户界面。PromptForChoice()也不$host.用户界面。RawUI.ReadKey().预先感谢任何的指针。

编辑:多谢谢你拉尔斯Truijens寻找答案。我已经采取了代码,他指出,封装成一个功能。注意,方式,我们实现这意味着有可能最多一秒之间的延迟时的用户命中的一个关键和脚本时继续执行。

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/704920a4a43f06f4f0d2

等待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.")

示例脚本输出:

参考 Microsoft文档

致谢: Technet Link

这里是一个按键的实用功能接受:

  • 验证符集(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