2017-06-16 61 views
0

我正在研究一个简单的脚本,但我为此目瞪口呆,为什么某些东西不能正常工作。我的脚本计算出电脑已打开多长时间并将其打印到屏幕上。如果我只打印一次然后退出,格式化就可以了。但是,如果我把它放在一个循环中以便不断更新,即使我有线程休眠,格式化也是关闭的。下面是代码:Powershell脚本文本在循环中的格式不正确但没有循环

打印和退出

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

在此先感谢您的帮助。

回答

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 
}