Files
management-scripts/Restart-EndpointOnUptime.ps1
T

21 lines
957 B
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:04:06 -05:00
Try { $LastBootUpTime = Get-WmiObject -Class Win32_OperatingSystem1 -ErrorAction SilentlyContinue | Select-Object -ExpandProperty LastBootUpTime }
Catch { Write-Error $_.Exception.Message }
2024-02-28 13:51:44 -05:00
$LastBootUpTime = [Management.ManagementDateTimeConverter]::ToDateTime($LastBootUpTime)
# 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
}
}