73 lines
2.6 KiB
PowerShell
73 lines
2.6 KiB
PowerShell
Set-StrictMode -Version Latest
|
|
|
|
function Invoke-LocalRebootOnRemoteUptime {
|
|
<#
|
|
.SYNOPSIS
|
|
Reboots local machine based on remote uptime. Optimized for RMM/NinjaRMM.
|
|
|
|
.PARAMETER RemoteComputerName
|
|
The target server to compare against.
|
|
.PARAMETER DryRun
|
|
If present, logs what would happen without actually rebooting.
|
|
#>
|
|
[CmdletBinding()]
|
|
param (
|
|
[Parameter(Mandatory = $true)]
|
|
[string]$RemoteComputerName,
|
|
|
|
[Parameter(Mandatory = $false)]
|
|
[switch]$DryRun
|
|
)
|
|
|
|
process {
|
|
$BasePath = $PSScriptRoot
|
|
$LogPath = Join-Path -Path $BasePath -ChildPath "Logs"
|
|
$Timestamp = Get-Date -Format "yyyyMMdd-HHmm"
|
|
$LogFile = Join-Path -Path $LogPath -ChildPath "UptimeCheck_$($Timestamp).txt"
|
|
|
|
try {
|
|
if (-not (Test-Path -Path $LogPath)) {
|
|
New-Item -Path $LogPath -ItemType Directory -Force | Out-Null
|
|
}
|
|
|
|
Write-Verbose "Testing connection to $RemoteComputerName..."
|
|
if (-not (Test-Connection -ComputerName $RemoteComputerName -Count 1 -Quiet)) {
|
|
Write-Error "Remote server $RemoteComputerName unreachable."
|
|
return
|
|
}
|
|
|
|
$LocalOS = Get-CimInstance -ClassName Win32_OperatingSystem -ErrorAction Stop
|
|
$RemoteOS = Get-CimInstance -ClassName Win32_OperatingSystem -ComputerName $RemoteComputerName -ErrorAction Stop
|
|
|
|
$LocalBoot = $LocalOS.LastBootUpTime
|
|
$RemoteBoot = $RemoteOS.LastBootUpTime
|
|
|
|
Write-Output "Local Boot: $LocalBoot | Remote Boot: $RemoteBoot"
|
|
|
|
if ($RemoteBoot -gt $LocalBoot) {
|
|
$Msg = "MATCH: Remote rebooted more recently. Local reboot required."
|
|
|
|
if ($DryRun) {
|
|
Write-Warning "[DRY RUN]: $Msg (Reboot suppressed by switch)"
|
|
$("[DRY RUN] " + $Msg) | Out-File -FilePath $LogFile -Append
|
|
}
|
|
else {
|
|
Write-Output "Executing Reboot..."
|
|
$Msg | Out-File -FilePath $LogFile -Append
|
|
# Force restart immediately for RMM context
|
|
Restart-Computer -Force -Confirm:$false
|
|
}
|
|
}
|
|
else {
|
|
Write-Output "No action needed. Local system is up to date."
|
|
}
|
|
}
|
|
catch {
|
|
Write-Error "Script Failed: $($_.Exception.Message)"
|
|
}
|
|
}
|
|
}
|
|
|
|
# NinjaRMM Script Variable Mapping (Example)
|
|
# Ensure you have a script variable in Ninja called 'RemoteServer'
|
|
Invoke-LocalRebootOnRemoteUptime -RemoteComputerName $RemoteComputerName |