【问题标题】:Calculate Date with PowerShell使用 PowerShell 计算日期
【发布时间】:2015-05-27 13:51:43
【问题描述】:

我正在尝试在 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
}

【问题讨论】:

    标签: powershell scripting system-administration


    【解决方案1】:

    让我们使用这个功能:

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

    【讨论】:

    • if (($dt.LastBootUpTime).AddHours($hour) 应该是... if (($lbt.LastBootUpTime).AddHours($hour) 谢谢。
    【解决方案2】:

    这可以工作:

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

    【讨论】:

    • [math]::Abs() 并不是真正需要的,除非您预计最后一次启动时间是将来的某个时间。只需反转减法即可。
    • @EBGreen 谁知道是否有人将时间提前了? :-P
    • 你没有,但如果他们有,那么 Get-Date 也会向前移动。另外,如果他们在玩弄时间,那么计算自上次重启以来的时间无论如何都是没有意义的。
    • @EBGreen 你太认真了......保持冷静和放松;)
    【解决方案3】:

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

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

    【讨论】:

      【解决方案4】:

      这是一个使用ticks 比较的单行代码

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-11-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多