0

I'm working on a simple script but I'm dumbfounded why a certain thing isn't working. My script calculates how long the computer has been on and prints it to the screen. If I have it print just once and then exit, the formatting is fine. However, if I put it in a loop so it is constantly updating, the formatting is off, even if I have the thread sleep. Here is the code:

Print and Exit

    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

And its output:

  ____________
  Hours Worked
  ____________

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

Loop

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)

and its refreshing output

  ____________
  Hours Worked
  ____________
    2      30

I know this isn't a big deal, but I think understanding this problem will help me understand Powershell scripting a little better.

Thanks in advance for any help.

1 Answer 1

2

I think this is probably what you are trying to do:

$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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.