Skip to content

Instantly share code, notes, and snippets.

@espoelstra
Forked from altrive/Test-RebootRequired.ps1
Last active April 4, 2017 16:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save espoelstra/a61bceb1f1e240628971e528aaf69a45 to your computer and use it in GitHub Desktop.
Save espoelstra/a61bceb1f1e240628971e528aaf69a45 to your computer and use it in GitHub Desktop.
Check pending reboot on local computer (2008R2 and 2012R2 compatible ErrorAction)

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 SilentlyContinue
if ($key -ne $null)
{
$result.CBSRebootPending = $true
}
#Check Windows Update
$key = Get-Item "HKLM:SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired" -ErrorAction SilentlyContinue
if($key -ne $null)
{
$result.WindowsUpdateRebootRequired = $true
}
#Check PendingFileRenameOperations
$prop = Get-ItemProperty "HKLM:SYSTEM\CurrentControlSet\Control\Session Manager" -Name PendingFileRenameOperations -ErrorAction SilentlyContinue
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)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment