使用 PowerShell 计算日期

Calculate Date with PowerShell

我正在尝试在 Powershell 中创建一个脚本;

获取 PC 的上次启动时间并检查它是否大于 48 小时 如果它更大 重启机器 否则退出

我似乎无法正确计算它。

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
}

这可行:

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

让我们使用这个函数:

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

你可以测试:

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

使用 SWbemDateTime 对象将 WMI 时间字符串转换为可以与 Get-Date 值进行比较的 DateTime 对象:

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