Use remediations in Intune - more at https://learn.microsoft.com/en-us/mem/intune/fundamentals/remediations
- Detection script (check uptime) This script will check the uptime of the machine. If the uptime is more than 14 days, it will return a non-zero exit code to indicate that the condition was met.
$uptime = (Get-CimInstance -ClassName Win32_OperatingSystem).LastBootUpTime
$currentDate = Get-Date
$uptimeDuration = $currentDate - $uptime
# Check if uptime is greater than 14 days
if ($uptimeDuration.Days -gt 14) {
Write-Output "Uptime is greater than 14 days. Remediation required."
exit 1 # Non-zero exit code indicates the condition is met
} else {
Write-Output "Uptime is less than or equal to 14 days."
exit 0 # Zero exit code indicates the condition is not met
}
- Remediation script (force reboot or notify and reboot) If the detection script finds that the uptime exceeds 14 days, the remediation script will then run. It will check if there is an active user logged in, and based on that, it will either force a reboot or show a warning and reboot after 10 minutes.
# Check if a user is logged in
$loggedInUser = (query user) | Where-Object { $_ -match '^\s*(\w+)' } | Select-String -Pattern '\w+' | ForEach-Object { $_.Matches.Groups[0].Value }
if ($loggedInUser) {
# If a user is logged in, notify them
$message = "Save your work because in 10 minutes your PC will restart."
$title = "System Restart Warning"
# Display warning message to the user
Add-Type -TypeDefinition @"
using System;
using System.Windows.Forms;
public class MessageBoxExample {
public static void ShowMessage(string message) {
MessageBox.Show(message, "$title", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
"@
[MessageBoxExample]::ShowMessage($message)
# Wait for 10 minutes (600 seconds)
Start-Sleep -Seconds 600
# Reboot the machine
Restart-Computer -Force
} else {
# If no user is logged in, force reboot immediately
Restart-Computer -Force
}
- Deployment in Intune:
- Upload and deploy the detection script as a "PowerShell Script" in Intune (under Devices > Manage devices> Scripts and remediations).
You'll need to ensure that the remediation script runs with the appropriate privileges (you can configure this to run as System if needed). The
query user
command assumes that there is a command prompt environment and that the user is logged in interactively. If using a non-interactive session, you might need to adjust this check. TheStart-Sleep
command is used for a 10-minute wait before restarting the machine, and the warning message is shown using a Windows Forms pop-up.
If the above response helps answer your question, remember to "Accept Answer" so that others in the community facing similar issues can easily find the solution. Your contribution is highly appreciated.
hth
Marcin