2017-06-16 93 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 
}