如何在powershell中停止包含start-sleep的while($true)

use*_*354 4 powershell ping keypress exit

我的谷歌-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"
}
Run Code Online (Sandbox Code Playgroud)

Jan*_*lka 5

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

$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
    }    
}
Run Code Online (Sandbox Code Playgroud)

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