【问题标题】:Press hotkey to rerun script during a loop but don't wait for it在循环期间按热键重新运行脚本,但不要等待它
【发布时间】:2017-02-08 04:22:39
【问题描述】:

基本上我有一个运行的脚本,它开始睡眠 30 分钟,然后再次循环并重新运行。我想知道是否有一种方法可以单击窗口,按热键,然后手动刷新?

 while($true){
    $data = @("device1", "device2")

    ForEach ($server in $data) {

    ping $server

start-sleep 1800
clear
     }
    }

【问题讨论】:

  • 我不知道,因为我什至不知道如何启动它,除非你的意思是我的循环脚本,然后我添加了一个如何循环的小例子。
  • 所以我看不出这个脚本有什么问题,你缺少什么?
  • 好吧,我在这个线程上的问题是是否有办法在它处于开始睡眠状态时按下热键重新运行它。
  • 好的,现在我终于明白你在说什么了,所以用热键“打破”睡眠,对吧,再循环一遍?
  • 脚本运行后休眠 30 分钟,希望能够按下热键,然后它会中断并重新启动脚本。以防万一您不想等待 30 分钟。

标签: loops powershell keyboard-shortcuts


【解决方案1】:

我通过其他方法发现以下允许我检查屏幕是否有任何按键,如果有按键则中断,但仍处于开始睡眠状态。

$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】:

    我猜,你最好的办法是在你的主 while 循环中实现一个 for 循环,它每 5-15 秒检查一次按键,如果它检测到,它会自行中断,所以你的 while 循环可以启动结束了,这里有一些似乎相关的链接:

    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?

    【讨论】:

      猜你喜欢
      • 2020-04-18
      • 1970-01-01
      • 2019-05-16
      • 2011-11-15
      • 1970-01-01
      • 2015-04-07
      • 1970-01-01
      • 1970-01-01
      • 2013-03-20
      相关资源
      最近更新 更多