【问题标题】:Powershell script text doesn't format correctly when in a loop but does without loopPowershell 脚本文本在循环中时格式不正确,但在没有循环时会正确
【发布时间】:2017-06-16 14:44:36
【问题描述】:

我正在编写一个简单的脚本,但我很困惑为什么某些东西不起作用。我的脚本会计算计算机的运行时间并将其打印到屏幕上。如果我只打印一次然后退出,则格式很好。但是,如果我把它放在一个循环中以便它不断更新,那么即使我让线程休眠,格式也会关闭。这是代码:

打印并退出

    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 脚本。

提前感谢您的帮助。

【问题讨论】:

    标签: powershell scripting output powershell-ise


    【解决方案1】:

    我认为这可能是你想要做的:

    $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
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-03
      • 1970-01-01
      • 1970-01-01
      • 2013-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多