Saltar al contenido
Microsoft scripts

Scripts de Intune

Detectar reinicios pendientes con más de 2 días

Detecta equipos con reinicio pendiente (servicio de componentes, Windows Update, renombrado de equipo) y al menos 2 días encendidos. Con exit 1 dispara la corrección que programa el reinicio.

Antes de correrloSolo lee. Microsoft recomienda no poner comandos de reinicio en scripts de Remediaciones; si lo usas solo para detectar, no hay problema. El permiso de Graph del encabezado no lo usa el código.

Ejemplo en México

Empacadora agrícola en Culiacán, 60 equipos de oficina

Los equipos de oficina nunca reinician y las actualizaciones de seguridad quedan a medias.

detect-reboot-pending.ps1

Obtiene la lista de equipos con reinicio pendiente por más de 2 días.

Cómo implementarlo

  1. En el centro de administración de Microsoft Intune ve a Dispositivos > Administrar dispositivos > Scripts y correcciones (Scripts and remediations) > Remediations > Crear paquete de scripts.
  2. En Configuración sube detect-reboot-pending.ps1 como script de detección y remediate-reboot-pending.ps1 como script de corrección.
  3. Deja desactivadas "Ejecutar con las credenciales del usuario" y "Aplicar verificación de firma", asígnalo primero a un grupo piloto y elige la frecuencia.
  4. Revisa en el paquete cuántos equipos tienen reinicio pendiente.
Ver el código completo de detect-reboot-pending.ps1
<#
.TITLE
    Reboot Pending Detection Script

.SYNOPSIS
    Detects devices that have a pending reboot older than the configured threshold.

.DESCRIPTION
    Checks the standard Windows pending-reboot signals: Component Based Servicing,
    Windows Update, pending file rename operations, and pending computer rename.
    Returns exit code 1 when a reboot is pending and the device has been up longer
    than the minimum uptime threshold, triggering the paired remediation that
    schedules a restart with user warning.

.TAGS
    Remediation,Detection

.REMEDIATIONTYPE
    Detection

.PAIRSCRIPT
    remediate-reboot-pending.ps1

.PLATFORM
    Windows

.MINROLE
    Intune Service Administrator

.PERMISSIONS
    DeviceManagementManagedDevices.ReadWrite.All

.AUTHOR
    Ugur Koc

.VERSION
    1.0

.CHANGELOG
    1.0 - Initial release

.LASTUPDATE
    2026-07-20

.EXAMPLE
    .\detect-reboot-pending.ps1
    Returns exit 1 if a reboot is pending and uptime exceeds the threshold

.NOTES
    - Runs in SYSTEM context via Intune Remediations
    - $MinimumUptimeDays avoids flagging devices that rebooted recently but picked up a new pending flag
    - PendingFileRenameOperations alone is noisy (installers set it constantly), so it only counts together with uptime
#>

$ErrorActionPreference = "Stop"

# Only flag devices that have not rebooted for at least this long
$MinimumUptimeDays = 2

function Test-PendingReboot {
    $reasons = [System.Collections.Generic.List[string]]::new()

    if (Test-Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending") {
        $reasons.Add("Component Based Servicing")
    }

    if (Test-Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired") {
        $reasons.Add("Windows Update")
    }

    try {
        $pendingRenames = (Get-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager" -Name PendingFileRenameOperations -ErrorAction SilentlyContinue).PendingFileRenameOperations
        if ($pendingRenames) {
            $reasons.Add("Pending file rename operations")
        }
    }
    catch {
        # Value not present - nothing pending
    }

    try {
        $activeName = (Get-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\ComputerName\ActiveComputerName" -Name ComputerName -ErrorAction SilentlyContinue).ComputerName
        $pendingName = (Get-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\ComputerName\ComputerName" -Name ComputerName -ErrorAction SilentlyContinue).ComputerName
        if ($activeName -and $pendingName -and $activeName -ne $pendingName) {
            $reasons.Add("Pending computer rename ($activeName -> $pendingName)")
        }
    }
    catch {
        # Ignore - rename detection is best effort
    }

    return @($reasons)
}

try {
    $lastBoot = (Get-CimInstance -ClassName Win32_OperatingSystem).LastBootUpTime
    $uptimeDays = [math]::Round(((Get-Date) - $lastBoot).TotalDays, 1)

    $pendingReasons = Test-PendingReboot

    if ($pendingReasons.Count -eq 0) {
        Write-Output "No reboot pending. Uptime: $uptimeDays days."
        exit 0
    }

    if ($uptimeDays -lt $MinimumUptimeDays) {
        Write-Output "Reboot pending ($($pendingReasons -join '; ')) but uptime is only $uptimeDays days - below the $MinimumUptimeDays day threshold."
        exit 0
    }

    Write-Output "Reboot pending for $uptimeDays days: $($pendingReasons -join '; ')"
    exit 1
}
catch {
    Write-Error $_
    exit 2
}

# Copia sin cambios de https://github.com/ugurkocde/IntuneAutomation (commit 797bb2e).
# MIT License
#
# Copyright (c) 2025 Ugur Koc | Microsoft MVP
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

Relacionados