我有一个脚本启动一个事件并等待用户按任意键来停止脚本执行。我试图找到一种方法来显示计时器(脚本运行了多长时间),同时在Read-Host等待用户输入。有没有办法做到这一点?
这有效
$Time = [System.Diagnostics.Stopwatch]::StartNew()
while ($true) {
$CurrentTime = $Time.Elapsed
write-host $([string]::Format("`rTime: {0:d2}:{1:d2}:{2:d2}",
$CurrentTime.hours,
$CurrentTime.minutes,
$CurrentTime.seconds)) -nonewline
sleep 1
if ($Host.UI.RawUI.KeyAvailable -and ("q" -eq $Host.UI.RawUI.ReadKey("IncludeKeyUp,NoEcho").Character)) {
Write-Host "Exiting now"
break;
}
}