Powershell脚本文本在循环中无法正确格式化但没有循环

时间:2017-06-16 14:44:37

标签: powershell scripting output powershell-ise

我正在编写一个简单的脚本,但是我为什么某个东西不起作用而傻眼了。我的脚本计算计算机已打开的时间并将其打印到屏幕上。如果我只打印一次然后退出,格式化就可以了。但是,如果我将它放在一个循环中以便不断更新,则格式化将关闭,即使我有线程休眠。这是代码:

打印并退出

    Clear-Host
$Booted = (Get-WmiObject Win32_OperatingSystem).LastBootUpTime
$Booted = [Management.ManagementDateTimeConverter]::ToDateTime($Booted)

echo "  ____________"
echo "  Hours Worked"
echo "  ____________"
$now = [datetime]::now 
New-TimeSpan -Start $Booted -End $now | Select-Object -Wait Hours, Minutes

及其输出:

  ____________
  Hours Worked
  ____________

Hours Minutes
----- -------
    2      22

循环

Clear-Host
$Booted = (Get-WmiObject Win32_OperatingSystem).LastBootUpTime
$Booted = [Management.ManagementDateTimeConverter]::ToDateTime($Booted)

do {
Clear-Host
echo "  ____________"
echo "  Hours Worked"
echo "  ____________"
$now = [datetime]::now 
New-TimeSpan -Start $Booted -End $now | Select-Object -Wait Hours, Minutes
Start-Sleep -m 1000
} while (1)

及其刷新输出

  ____________
  Hours Worked
  ____________
    2      30

我知道这不是什么大问题,但我认为理解这个问题将有助于我更好地理解Powershell脚本。

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

我认为这可能就是你要做的事情:

$lastBoot = [Management.ManagementDateTimeConverter]::
  ToDateTime((Get-WmiObject Win32_OperatingSystem).LastBootUpTime)

while ( $true ) {
  $timeWorked = (Get-Date) - $lastBoot
  Clear-Host
  [PSCustomObject] @{
    "Hours"   = $timeWorked.Hours
    "Minutes" = $timeWorked.Minutes
  } | Out-String
  Start-Sleep 1
}
相关问题