Skip to content

Instantly share code, notes, and snippets.

@altrive
Last active August 3, 2023 14:34
Show Gist options
  • Save altrive/5329377 to your computer and use it in GitHub Desktop.
Save altrive/5329377 to your computer and use it in GitHub Desktop.
Check pending reboot on local computer

Usage

#Local Computer

if(Test-RebootRequired)
{
    Restart-Computer -Force
}

#Remote Computer

$params = @{
    ComputerName = "172.16.100.64"
    Credential = Get-Credential -UserName "localhost\Administrator" -Message "Enter Password"
    Authentication = "Default"
    ScriptBlock = ${function:Test-RebootRequired}
}

#Check Reboot is required to remote computer
$isRebootRequired = Invoke-Command @params

if($isRebootRequired -eq $true)
{
    #Restart and wait until WinRM available
    Restart-Computer -ComputerName $params.ComputerName -Credential $params.Credential -WsmanAuthentication Default -Force -Wait -For WinRM
}

#Check Reboot is required to remote computer
$isRebootRequired = Invoke-Command @params
if($isRebootRequired -eq $true)
{
    throw "Reboot required once more!"
}
#Based on <http://gallery.technet.microsoft.com/scriptcenter/Get-PendingReboot-Query-bdb79542>
function Test-RebootRequired
{
$result = @{
CBSRebootPending =$false
WindowsUpdateRebootRequired = $false
FileRenamePending = $false
SCCMRebootPending = $false
}
#Check CBS Registry
$key = Get-ChildItem "HKLM:Software\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending" -ErrorAction Ignore
if ($key -ne $null)
{
$result.CBSRebootPending = $true
}
#Check Windows Update
$key = Get-Item "HKLM:SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired" -ErrorAction Ignore
if($key -ne $null)
{
$result.WindowsUpdateRebootRequired = $true
}
#Check PendingFileRenameOperations
$prop = Get-ItemProperty "HKLM:SYSTEM\CurrentControlSet\Control\Session Manager" -Name PendingFileRenameOperations -ErrorAction Ignore
if($prop -ne $null)
{
#PendingFileRenameOperations is not *must* to reboot?
#$result.FileRenamePending = $true
}
#Check SCCM Client <http://gallery.technet.microsoft.com/scriptcenter/Get-PendingReboot-Query-bdb79542/view/Discussions#content>
try
{
$util = [wmiclass]"\\.\root\ccm\clientsdk:CCM_ClientUtilities"
$status = $util.DetermineIfRebootPending()
if(($status -ne $null) -and $status.RebootPending){
$result.SCCMRebootPending = $true
}
}catch{}
#Return Reboot required
return $result.ContainsValue($true)
}
@hakong
Copy link

hakong commented Apr 14, 2016

-ErrorAction Ignore does not seem to work on Windows Server 2008 R2 or earlier, but -ErrorAction SilentlyContinue does work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment