我试图在xx分钟内每3秒运行一次循环。 while循环内部是一个IF语句。如果该语句为true,则关闭我的命令并再次重新启动循环达预定义的分钟数。
如果if语句在定义的分钟后永远不为真,则触发我的命令,然后使用上面设置的时间重新开始循环。
我可以在带有goto的批处理文件中执行此操作,但无法弄清楚如何在PowerShell中执行此操作。
这是我想要完成的事情的表示。
$minutes = 5
while(loop for 5 minutes)
{
if(1 -eq 1)
{
do something
restart the while loop for the minutes defined above
}
start-sleep -seconds 3
}
do something here
restart the while loop for the minutes defined above
更新
这是我想出的。这是我第一次尝试在PowerShell中编写脚本,所以我几乎可以肯定有一种更优雅的方式来编写它。
# we need a constant loop going
while(1 -eq 1)
{
# now we need our timed loop. set the timer -seconds 3 (3 seconds right now for testing)
$timeout = new-timespan -seconds 3
$sw = [diagnostics.stopwatch]::StartNew()
while ($sw.elapsed -lt $timeout)
{
# check to see if things are still true
if($something -eq "true")
{
echo "Do nothing."
}
else
{
echo "Do something and restart."
# break out of this timed loop since we want to restart it
break
}
# check every 1 second
start-sleep -seconds 1
}
echo "$something did not equal true in the IF above or the timer has run out. Do something and restart."
# continue restarts the loop
continue
}
答案 0 :(得分:2)
你不能重置$ sw吗?
<top (required)>'
from bin/rails:9:in