Files
management-scripts/Restart-EndpointOnUptime.ps1
T

21 lines
1.1 KiB
PowerShell
Raw Normal View History

2024-02-28 15:23:06 -05:00
# Function to restart an endpoint that has not been restarted for the specified number of hours
2024-02-28 14:01:00 -05:00
Function Restart-EndpointOnUptime ([int]$MaxUptimeHours) {
2024-02-28 13:51:44 -05:00
2024-02-28 15:23:06 -05:00
# Exit if the specified number of hours is not greater than 0
If ( !($MaxUptimeHours -gt 0) ) { Write-Output "Must specify 1 or more hours" ; Exit }
2024-02-28 14:18:09 -05:00
# Get the last boot up time as a DateTime
2024-02-28 15:23:06 -05:00
$LastBootTime = [Management.ManagementDateTimeConverter]::ToDateTime($(Get-WmiObject -Class Win32_OperatingSystem -ErrorAction Stop | Select-Object -ExpandProperty LastBootUpTime))
# Get the total number of hours the endpoint has been up
$UptimeHours = $($(Get-Date) - $LastBootTime).TotalHours
2024-02-28 13:51:44 -05:00
2024-02-28 15:23:06 -05:00
# If $Uptime is greater than $MaxUptimeHours, restart the endpoint
If ( $UptimeHours -gt $MaxUptimeHours) {
Write-Output "This endpoint has been up for at least ${UptimeHours} hours and will be restarted now"
Start-Sleep -Seconds 5
Restart-Computer -Force
} Else {
Write-Output "This endpoint has already been restarted within the last ${MaxUptimeHours} hours"
2024-02-28 13:51:44 -05:00
}
}