如何在powershell中包含启动睡眠的($true)时停止

如何在powershell中包含启动睡眠的($true)时停止,powershell,keypress,ping,exit,Powershell,Keypress,Ping,Exit,我的谷歌fu让我失望了。我有一个非常简单的脚本,它只测试从一台服务器到另一台服务器的ping连接,并在顶部显示一个运行时 我希望能够在任何时候用一个键停止这个脚本(“脚本中的q”),并让它给出一些基本的统计信息,说明它运行了多长时间,失败了多少次 我可以用ctrl+c停止脚本,但这完全不允许我显示任何统计信息。下面是我的脚本。感谢您的帮助 ###############SETTINGS########################## #Server to Ping: $RemoteMach

我的谷歌fu让我失望了。我有一个非常简单的脚本,它只测试从一台服务器到另一台服务器的ping连接,并在顶部显示一个运行时

我希望能够在任何时候用一个键停止这个脚本(“脚本中的q”),并让它给出一些基本的统计信息,说明它运行了多长时间,失败了多少次

我可以用ctrl+c停止脚本,但这完全不允许我显示任何统计信息。下面是我的脚本。感谢您的帮助

###############SETTINGS##########################

#Server to Ping:
$RemoteMachine = "ServerNameorIP"

#Seconds between each ping:
$PingInterval = 5

#File to log results:
$outFile = "C:\PingLog\"+$today+".PingLog.txt"

##################################################


$today = Get-Date -Format "yyyy-MM-dd"

#start a stopwatch for the progress bar
$elapsedTime = [system.diagnostics.stopwatch]::StartNew()

while ($true)
    {
   #Stick a progress bar at the top that shows elapsed time and how often we're pinging:
   write-progress -activity "Now testing ping connectivity to $RemoteMachine every $PingInterval seconds.  Press q to quit." -status "$([string]::Format("Time Elapsed: {0:d2}:{1:d2}:{2:d2}", $elapsedTime.Elapsed.hours, $elapsedTime.Elapsed.minutes, $elapsedTime.Elapsed.seconds))"

   $pingFails = 0

    #If the ping test fails, say something, and write it out to a log
    if(!(Test-Connection -ComputerName bb-ts-db -Quiet))
        {
        $pingFails++
        $dropTime = Get-Date -Format "MM/dd/yyyy - HH:mm:ss"
        Add-Content -Path $outfile -value ("Connection Lost at:  $dropTime")
        Echo "Connection Lost at $dropTime"
        }


    #Exit the loop if a key is pressed:
    if ($Host.UI.RawUI.KeyAvailable -and ("q" -eq $Host.UI.RawUI.ReadKey("IncludeKeyUp,NoEcho").Character)) 
    {
        Write-Host "Exiting now, don't try to stop me...." -Background DarkRed
        break;
    }

    #Wait the preset amount of time between each ping loop
    Start-Sleep $pingInterval
}


$elapsedTime.stop()

#Display the stats of this session:
echo "Test runtime:       $elapsedTime.Elapsed"
echo "# of failed pings:  $pingFails"

#If there WERE ping fails, write stats to $outFile
if($pingFails -gt 0)
{
    Add-content -Path $outfile -value "`n `n `n"
    Add-content -Path $outfile -value "Test runtime:       $elapsedTime.Elapsed"
    Add-content -Path $outfile -value "# of failed pings:  $pingFails"
}

这篇文章是类似的。此时将捕获CTRL-C并用于退出循环/脚本


下面是一个使用[console]:KeyAvailable方法的简单示例。为了使其可用,您必须更频繁地唤醒循环,并且只在每10次(,大约)唤醒时执行ping。(如果这有道理的话。)


注意:不幸的是[console]::KeyAvailable在PowerShellise主机中不起作用,因此调试起来很麻烦:(

当您没有开始睡眠或其他需要时间运行的命令时,这项功能会起作用,但一旦您开始睡眠,脚本运行的99%时间都发生在检查按键的if语句之外,这与我上面遇到的问题相同。是否有办法让它随时检查按键?您可以uld将ping作为作业运行,然后执行
do{}While((Get Job-State Running))
循环,尽管这种循环会杀死整个进度条位。很好,但我必须使用
Sleep 1;清除
,因为
开始睡眠-500毫秒
返回了一个错误
$continue = $true
while($continue)
{
    if ([console]::KeyAvailable)
    {
        echo "Exit with `"q`"";
        $x = [System.Console]::ReadKey() 

        switch ( $x.key)
        {
            q { $continue = $false }
        }
    } 
    else
    {
        # Your while loop commands go  here......
        Start-Sleep -Milliseconds 500
    }    
}