# Get the current script directory
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$Log = Join-Path $ScriptDir "log.txt"
Start-Transcript -Path $Log -Force
# Path to MSU inside deployment folder
$MSU = (Get-ChildItem -Path "$($ScriptDir)\" -File | where { $_.Name -Like "*.msu" }).FullName
if($MSU -match 'kb(\d{7})'){
$kb = "kb$($matches[1])"
}
Write-host "Installing $kb"
# Install silently
Start-Process wusa.exe -ArgumentList "`"$MSU`" /quiet /norestart" -Wait
sleep 3
# If install succeeded
$installed = Get-WmiObject -Class Win32_QuickFixEngineering | Where-Object {$_.HotFixID -eq $kb}
if ($installed) {
Write-Host "Finished"
# Detect interactive users (console or RDP)
$InteractiveUsers = Get-CimInstance Win32_LoggedOnUser |
ForEach-Object {
$session = $_.Dependent -replace '"',''
if ($session -match "LogonId = (\d+)") {
$logonId = $matches[1]
Get-CimInstance Win32_LogonSession -Filter "LogonId = $logonId"
}
} |
Where-Object { $_.LogonType -in 2,10 }
if ($InteractiveUsers) {
Write-Host "User(s) Found."
# User is logged in → show SCCM reboot toast
New-ItemProperty "Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\SMS\Mobile Client\Reboot Management\RebootData" -Name RebootBy -Value 0 -Force -WarningAction SilentlyContinue -ErrorAction SilentlyContinue
Write-Host "Restarting CCM Agent"
Restart-Service ccmexec -force -WarningAction SilentlyContinue -ErrorAction SilentlyContinue
sleep 5
Start-Process "C:\Windows\CCM\SCNotification.exe" -ArgumentList '/RestartRequired'
}
else {
Write-Host "Rebooting"
# No user logged in → reboot immediately
shutdown.exe /r /t 0
}
}
Stop-Transcript