Files
management-scripts/Restart-EndpointOnUptime.ps1
T

24 lines
1.0 KiB
PowerShell
Raw Normal View History

2024-02-28 14:01:00 -05:00
Function Restart-EndpointOnUptime ([int]$MaxUptimeHours) {
2024-02-28 13:51:44 -05:00
# Check the last boot up time
2024-02-28 14:05:46 -05:00
Try {
2024-02-28 14:08:20 -05:00
$LastBootUpTime = Get-WmiObject -Class Win32_OperatingSystem1 -ErrorAction Stop | Select-Object -ExpandProperty LastBootUpTime
2024-02-28 14:05:46 -05:00
$LastBootUpTime = [Management.ManagementDateTimeConverter]::ToDateTime($LastBootUpTime)
}
2024-02-28 14:09:44 -05:00
Catch [Exception] { Write-Error $_.Exception.Message ; Write-Output "Cannot restart this computer" ; Exit }
2024-02-28 14:05:46 -05:00
2024-02-28 13:51:44 -05:00
# Calculate the difference in hours
$CurrentTime = Get-Date
$TimeDifference = $CurrentTime - $LastBootUpTime
$DifferenceInHours = $TimeDifference.TotalHours
2024-02-28 14:01:00 -05:00
# Check if the difference is greater than $MaxUptimeHours
If ($DifferenceInHours -gt $MaxUptimeHours) {
2024-02-28 13:51:44 -05:00
# Restart the computer
2024-02-28 14:01:00 -05:00
Write-Output "Restarting computer because it has not been restarted in the last ${MaxUptimeHours} hours."
2024-02-28 14:04:06 -05:00
Restart-Computer
2024-02-28 13:51:44 -05:00
} Else {
2024-02-28 14:01:00 -05:00
Write-Output "No need to restart. The last restart was within ${MaxUptimeHours} hours."
2024-02-28 13:51:44 -05:00
}
}