简体   繁体   中英

Calculate Date with PowerShell

I am trying to create a script in Powershell that will;

Get Last Bootup Time of the PC and check if it's greater than 48hrs If it's greater Reboot machine Else exit

I can't seem to get it to calculate correctly.

cls
# Declaring Variables

$lbt = Get-CimInstance -ClassName win32_operatingsystem | Select LastBootUpTime
$lbt = $lbt.lastbootuptime
$ts = "{0:t}" -f $lbt
$texp = $lbt.AddHours(0)
#$ts = New-TimeSpan -Hours +3  #48 Hours Time Span from the last Boot Up Time

# Get Last Boot Up Time and compare
# Check LastBootUpTime
# If LastBootUpTime is grater than 48hrs continue executing ELSE RemoveIfExist -eq $true


Write-host "Last Boot      : " $lbt
write-host "Now            : " (Get-Date) `n


If ($lbt -ge $texp) {
Write-Host "Last Boot have been MORE than" ("{0:t}" -f $texp) hrs `n`n`n
}
else {
write-host "Last Boot have been LESS then" ("{0:t}" -f $texp) hrs `n`n`n
}

this can work:

$lbt = Get-CimInstance -ClassName win32_operatingsystem | Select LastBootUpTime
$now = get-date

if ( [math]::abs(($lbt.lastbootuptime - $now).totalhours) -gt 48 ) 
{
   "Last Boot have been MORE than 48 hrs ago"
}
else 
{
   "Last Boot have been LESS then 48 hrs ago"
}

Let's use this function :

function LastBootUpMoreThan ($hour){
  $dt = Get-CimInstance -ClassName win32_operatingsystem | Select LastBootUpTime
  if (($dt.LastBootUpTime).AddHours($hour) -gt (get-date)) {$false}else {$true}
}

You can test :

 if ((LastBootUpMoreThan 48)){"Reboot"}else{"Don't reboot"}

Use an SWbemDateTime object to convert a WMI time string to a DateTime object that you can compare to Get-Date values:

$hours = 48

$lbt = Get-WmiObject -Class Win32_OperatingSystem |
       select -Expand LastBootUpTime

$convert = New-Object -COM 'WbemScripting.SWbemDateTime'
$convert.Value = $lbt

if ($convert.GetVarDate() -ge (Get-Date).AddHours(-$hours)) {
  Write-Host "Last Boot have been MORE than $hours hours."
} else {
  Write-Host "Last Boot have been LESS than $hours hours."
}

这是一个使用ticks进行比较的班轮

 if (((Get-Date).Ticks) -gt ((Get-CimInstance -ClassName win32_operatingsystem | Select LastBootUpTime).LastBootUpTime.Ticks+(New-TimeSpan -Hours +48).ticks)) { "Reboot" }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM