24 lines
1019 B
PowerShell
24 lines
1019 B
PowerShell
Function Restart-EndpointOnUptime ([int]$MaxUptimeHours) {
|
|
|
|
# Check the last boot up time
|
|
Try {
|
|
$LastBootUpTime = Get-WmiObject -Class Win32_OperatingSystem1 -ErrorAction Stop | Select-Object -ExpandProperty LastBootUpTime
|
|
$LastBootUpTime = [Management.ManagementDateTimeConverter]::ToDateTime($LastBootUpTime)
|
|
}
|
|
Catch { Write-Error $_.Exception.Message ; Write-Output "Cannot restart this computer" ; Exit }
|
|
|
|
|
|
# Calculate the difference in hours
|
|
$CurrentTime = Get-Date
|
|
$TimeDifference = $CurrentTime - $LastBootUpTime
|
|
$DifferenceInHours = $TimeDifference.TotalHours
|
|
|
|
# Check if the difference is greater than $MaxUptimeHours
|
|
If ($DifferenceInHours -gt $MaxUptimeHours) {
|
|
# Restart the computer
|
|
Write-Output "Restarting computer because it has not been restarted in the last ${MaxUptimeHours} hours."
|
|
Restart-Computer
|
|
} Else {
|
|
Write-Output "No need to restart. The last restart was within ${MaxUptimeHours} hours."
|
|
}
|
|
} |