PowerShell Get-Date不刷新for循环

时间:2018-08-27 07:45:43

标签: powershell datetime

我有以下代码:

$date=  "{0:T}" -f (get-date)

for($i=1; $i -le 18000; $i++){
 if (Test-Connection 8.8.8.8 -count 1 -quiet )
  {
    write-Host "Success"
   }
  else
   {
   Add-Content $LogFile "`r`n`r`n Ping Failed at at " $date " `r`n "
  }
    Start-Sleep -Seconds 1
}

问题是我的$date始终保持静态。这意味着当ping操作失败时,时间总是相同的

为什么会这样,我该如何解决?

1 个答案:

答案 0 :(得分:3)

这是因为Get-Date仅执行一次(将其分配给变量,它不属于for循环)。解决方案:您必须将其放入for循环中:

for($i=1; $i -le 18000; $i++){
 if (Test-Connection 8.8.8.8 -count 1 -quiet )
  {
    write-Host "Success"
   }
  else
   {
   $date=  "{0:T}" -f (get-date)
   Add-Content $LogFile "`r`n`r`n Ping Failed at at " $date " `r`n "
  }
    Start-Sleep -Seconds 1
}