繁体   English   中英

使用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" }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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