0

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
     }
    }
Aaron
  • 3,135
  • 20
  • 51
  • 78
  • I do not because I have no idea how that would even be initiated, unless you mean my script that loops, then i added a small example of how that loops. – Aaron Feb 03 '17 at 17:38
  • so I see nothing wrong with this script, what is that you are missing? – 4c74356b41 Feb 03 '17 at 17:44
  • Well, my question on this thread is if there is a way to press a hotkey to rerun it when it is in a start-sleep status. – Aaron Feb 03 '17 at 17:49
  • ok, now I finally understand what you are talking, so "break" the sleep with a hotkey, right and go through the loop again? – 4c74356b41 Feb 03 '17 at 17:50
  • Script sleeps for 30min after it runs, would like to be able to press a hotkey and then it will break and restart the script. Just in case you dont want to wait 30 minutes. – Aaron Feb 03 '17 at 18:04

2 Answers2

2

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          

     }
Aaron
  • 3,135
  • 20
  • 51
  • 78
1

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?

Community
  • 1
  • 1
4c74356b41
  • 69,186
  • 6
  • 100
  • 141