问题
Basically I have a script that runs and it Start-Sleep for 30 minutes then loops around again and re-runs. I was wondering if there was a way where you could click on the window, press a hotkey, and have it just refresh manually?
while($true){
$data = @("device1", "device2")
ForEach ($server in $data) {
ping $server
start-sleep 1800
clear
}
}
回答1:
I found through other methods that the below has allowed me to check the screen for any key press and break if there is one, but still be in a start-sleep status.
$timeout = New-TimeSpan -Minutes 30
$sw = [diagnostics.stopwatch]::StartNew()
while ($sw.elapsed -lt $timeout){
if ($host.UI.RawUI.KeyAvailable) {
$key = $host.UI.RawUI.ReadKey()
break
}
start-sleep -seconds 5
}
回答2:
My guess, your best bet is to implement a for
loop inside your main while loop that does check for key press once every 5-15 seconds and if it detects that, it breaks itself, so your while loop can start over, here are a few links that seem to be relevant:
Waiting for user input with a timeout
https://blogs.msdn.microsoft.com/timid/2014/01/29/read-host-with-a-timeout-kind-of/
How to stop while($true) that contains start-sleep in powershell
Is there a way to catch ctrl-c and ask the user to confirm?
来源:https://stackoverflow.com/questions/42029709/press-hotkey-to-rerun-script-during-a-loop-but-dont-wait-for-it