Query Computer for Pending Reboot State (PS)

Ever needed to know if a reboot is pending on your computer? Try this Microsoft/Scripting Guy PowerShell script, and you’ll know!

Copy the code below and save as .ps1 file, and execute at your convenience.

Function Get-PendingReboot
{
<#
.SYNOPSIS
    Gets the pending reboot status on a local or remote computer.

.DESCRIPTION
    This function will query the registry on a local or remote computer and determine if the
    system is pending a reboot, from either Microsoft Patching or a Software Installation.
    For Windows 2008+ the function will query the CBS registry key as another factor in determining
    pending reboot state.  "PendingFileRenameOperations" and "Auto Update\RebootRequired" are observed
    as being consistant across Windows Server 2003 & 2008.
  
    CBServicing = Component Based Servicing (Windows 2008)
    WindowsUpdate = Windows Update / Auto Update (Windows 2003 / 2008)
    CCMClientSDK = SCCM 2012 Clients only (DetermineIfRebootPending method) otherwise $null value
    PendFileRename = PendingFileRenameOperations (Windows 2003 / 2008)

.PARAMETER ComputerName
    A single Computer or an array of computer names.  The default is localhost ($env:COMPUTERNAME).

.PARAMETER ErrorLog
    A single path to send error data to a log file.

.EXAMPLE
    PS C:\> Get-PendingReboot -ComputerName (Get-Content C:\ServerList.txt) | Format-Table -AutoSize
  
    Computer CBServicing WindowsUpdate CCMClientSDK PendFileRename PendFileRenVal RebootPending
    -------- ----------- ------------- ------------ -------------- -------------- -------------
    DC01     False   False           False      False
    DC02     False   False           False      False
    FS01     False   False           False      False

    This example will capture the contents of C:\ServerList.txt and query the pending reboot
    information from the systems contained in the file and display the output in a table. The
    null values are by design, since these systems do not have the SCCM 2012 client installed,
    nor was the PendingFileRenameOperations value populated.

.EXAMPLE
    PS C:\> Get-PendingReboot
  
    Computer     : WKS01
    CBServicing  : False
    WindowsUpdate      : True
    CCMClient    : False
    PendComputerRename : False
    PendFileRename     : False
    PendFileRenVal     : 
    RebootPending      : True
  
    This example will query the local machine for pending reboot information.
  
.EXAMPLE
    PS C:\> $Servers = Get-Content C:\Servers.txt
    PS C:\> Get-PendingReboot -Computer $Servers | Export-Csv C:\PendingRebootReport.csv -NoTypeInformation
  
    This example will create a report that contains pending reboot information.

.LINK
    Component-Based Servicing:
    http://technet.microsoft.com/en-us/library/cc756291(v=WS.10).aspx
  
    PendingFileRename/Auto Update:
    http://support.microsoft.com/kb/2723674
    http://technet.microsoft.com/en-us/library/cc960241.aspx
    http://blogs.msdn.com/b/hansr/archive/2006/02/17/patchreboot.aspx

    SCCM 2012/CCM_ClientSDK:
    http://msdn.microsoft.com/en-us/library/jj902723.aspx

.NOTES
    Author:  Brian Wilhite
    Email:   bcwilhite (at) live.com
    Date:    29AUG2012
    PSVer:   2.0/3.0/4.0/5.0
    Updated: 01DEC2014
    UpdNote: Added CCMClient property - Used with SCCM 2012 Clients only
       Added ValueFromPipelineByPropertyName=$true to the ComputerName Parameter
       Removed $Data variable from the PSObject - it is not needed
       Bug with the way CCMClientSDK returned null value if it was false
       Removed unneeded variables
       Added PendFileRenVal - Contents of the PendingFileRenameOperations Reg Entry
       Removed .Net Registry connection, replaced with WMI StdRegProv
       Added ComputerPendingRename
#>

[CmdletBinding()]
param(
  [Parameter(Position=0,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
  [Alias("CN","Computer")]
  [String[]]$ComputerName="$env:COMPUTERNAME",
  [String]$ErrorLog
  )

Begin {  }## End Begin Script Block
Process {
  Foreach ($Computer in $ComputerName) {
  Try {
      ## Setting pending values to false to cut down on the number of else statements
      $CompPendRen,$PendFileRename,$Pending,$SCCM = $false,$false,$false,$false
      
      ## Setting CBSRebootPend to null since not all versions of Windows has this value
      $CBSRebootPend = $null
            
      ## Querying WMI for build version
      $WMI_OS = Get-WmiObject -Class Win32_OperatingSystem -Property BuildNumber, CSName -ComputerName $Computer -ErrorAction Stop

      ## Making registry connection to the local/remote computer
      $HKLM = [UInt32] "0x80000002"
      $WMI_Reg = [WMIClass] "\\$Computer\root\default:StdRegProv"
            
      ## If Vista/2008 & Above query the CBS Reg Key
      If ([Int32]$WMI_OS.BuildNumber -ge 6001) {
        $RegSubKeysCBS = $WMI_Reg.EnumKey($HKLM,"SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\")
        $CBSRebootPend = $RegSubKeysCBS.sNames -contains "RebootPending"    
      }
              
      ## Query WUAU from the registry
      $RegWUAURebootReq = $WMI_Reg.EnumKey($HKLM,"SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\")
      $WUAURebootReq = $RegWUAURebootReq.sNames -contains "RebootRequired"
            
      ## Query PendingFileRenameOperations from the registry
      $RegSubKeySM = $WMI_Reg.GetMultiStringValue($HKLM,"SYSTEM\CurrentControlSet\Control\Session Manager\","PendingFileRenameOperations")
      $RegValuePFRO = $RegSubKeySM.sValue

      ## Query ComputerName and ActiveComputerName from the registry
      $ActCompNm = $WMI_Reg.GetStringValue($HKLM,"SYSTEM\CurrentControlSet\Control\ComputerName\ActiveComputerName\","ComputerName")      
      $CompNm = $WMI_Reg.GetStringValue($HKLM,"SYSTEM\CurrentControlSet\Control\ComputerName\ComputerName\","ComputerName")
      If ($ActCompNm -ne $CompNm) {
    $CompPendRen = $true
      }
            
      ## If PendingFileRenameOperations has a value set $RegValuePFRO variable to $true
      If ($RegValuePFRO) {
        $PendFileRename = $true
      }

      ## Determine SCCM 2012 Client Reboot Pending Status
      ## To avoid nested 'if' statements and unneeded WMI calls to determine if the CCM_ClientUtilities class exist, setting EA = 0
      $CCMClientSDK = $null
      $CCMSplat = @{
    NameSpace='ROOT\ccm\ClientSDK'
    Class='CCM_ClientUtilities'
    Name='DetermineIfRebootPending'
    ComputerName=$Computer
    ErrorAction='Stop'
      }
      ## Try CCMClientSDK
      Try {
    $CCMClientSDK = Invoke-WmiMethod @CCMSplat
      } Catch [System.UnauthorizedAccessException] {
    $CcmStatus = Get-Service -Name CcmExec -ComputerName $Computer -ErrorAction SilentlyContinue
    If ($CcmStatus.Status -ne 'Running') {
        Write-Warning "$Computer`: Error - CcmExec service is not running."
        $CCMClientSDK = $null
    }
      } Catch {
    $CCMClientSDK = $null
      }

      If ($CCMClientSDK) {
    If ($CCMClientSDK.ReturnValue -ne 0) {
      Write-Warning "Error: DetermineIfRebootPending returned error code $($CCMClientSDK.ReturnValue)"    
        }
        If ($CCMClientSDK.IsHardRebootPending -or $CCMClientSDK.RebootPending) {
      $SCCM = $true
        }
      }
      
      Else {
    $SCCM = $null
      }

      ## Creating Custom PSObject and Select-Object Splat
      $SelectSplat = @{
    Property=(
        'Computer',
        'CBServicing',
        'WindowsUpdate',
        'CCMClientSDK',
        'PendComputerRename',
        'PendFileRename',
        'PendFileRenVal',
        'RebootPending'
    )}
      New-Object -TypeName PSObject -Property @{
    Computer=$WMI_OS.CSName
    CBServicing=$CBSRebootPend
    WindowsUpdate=$WUAURebootReq
    CCMClientSDK=$SCCM
    PendComputerRename=$CompPendRen
    PendFileRename=$PendFileRename
    PendFileRenVal=$RegValuePFRO
    RebootPending=($CompPendRen -or $CBSRebootPend -or $WUAURebootReq -or $SCCM -or $PendFileRename)
      } | Select-Object @SelectSplat

  } Catch {
      Write-Warning "$Computer`: $_"
      ## If $ErrorLog, log the file to a user specified location/path
      If ($ErrorLog) {
    Out-File -InputObject "$Computer`,$_" -FilePath $ErrorLog -Append
      }        
  }      
  }## End Foreach ($Computer in $ComputerName)      
}## End Process

End {  }## End End

}## End Function Get-PendingReboot

Source: Microsoft Script Center

DIFxApp Configuration Flags (MSI)

Flag values for the DIFxApp merge module, to use in the MSIDriverPackages table when installing drivers in a MSI file. Remember to add the DIFxApp merge module, otherwise the driver will not be installed in the DriverStore.

This method is equivalent to DPinst.exe with a lot of switches.

Flag Description
1 Force driver installation
2 Suppress a prompt to connect a device
4 Suppress the creation of a Programs and Features entry for a driver package
8 Install an unsigned driver package
16 Remove installed files

Happy package building.

Source: Microsoft

Multiple Commands in one line (CMD)

Run multiple commands in one line with Windows Command Shell.

START /W CMD.EXE /C & C: & CD\ & DEL /F /S /Q "[filename]" >"%temp%\delete.log"
START /W CMD.EXE /C & DEL /F /Q "[path][filename]" >"%temp%\delete.log"

You can use the special characters listed in the following table to pass multiple commands.

CharacterSyntaxDefinition
& […]command1 & command2Use to separate multiple commands on one command line. Cmd.exe runs the first command, and then the second command.
&& […]command1 && command2Use to run the command following && only if the command preceding the symbol is successful. Cmd.exe runs the first command, and then runs the second command only if the first command completed successfully.
|| […]command1 || command2Use to run the command following || only if the command preceding || fails. Cmd.exe runs the first command, and then runs the second command only if the first command did not complete successfully (receives an error code greater than zero).
( ) […]( command1 & command2)Use to group or nest multiple commands.
; or ,command1 parameter1;parameter2Use to separate command parameters.

Note: The ampersand (&), pipe (|), and parentheses ( ) are special characters that must be preceded by the escape character (^) or quotation marks when you pass them as arguments

Note: This method can also be used in a .MSI package, through a Custom Action

Source: Microsoft

MSI Error Messages

A list of error codes (or return codes if you will), returned by Windows Installer functions ‘MsiExec.exe’ and ‘InstMSI.exe’.

Error code Value Description
ERROR_SUCCESS 0 The action completed successfully.
ERROR_INVALID_DATA 13 The data is invalid.
ERROR_INVALID_PARAMETER 87 One of the parameters was invalid.
ERROR_CALL_NOT_IMPLEMENTED 120 This value is returned when a custom action attempts to call a function that cannot be called from custom actions. The function returns the value ERROR_CALL_NOT_IMPLEMENTED. Available beginning with Windows Installer version 3.0.
ERROR_APPHELP_BLOCK 1259 If Windows Installer determines a product may be incompatible with the current operating system, it displays a dialog box informing the user and asking whether to try to install anyway. This error code is returned if the user chooses not to try the installation.
ERROR_INSTALL_SERVICE_FAILURE 1601 The Windows Installer service could not be accessed. Contact your support personnel to verify that the Windows Installer service is properly registered.
ERROR_INSTALL_USEREXIT 1602 The user cancels installation.
ERROR_INSTALL_FAILURE 1603 A fatal error occurred during installation.
ERROR_INSTALL_SUSPEND 1604 Installation suspended, incomplete.
ERROR_UNKNOWN_PRODUCT 1605 This action is only valid for products that are currently installed.
ERROR_UNKNOWN_FEATURE 1606 The feature identifier is not registered.
ERROR_UNKNOWN_COMPONENT 1607 The component identifier is not registered.
ERROR_UNKNOWN_PROPERTY 1608 This is an unknown property.
ERROR_INVALID_HANDLE_STATE 1609 The handle is in an invalid state.
ERROR_BAD_CONFIGURATION 1610 The configuration data for this product is corrupt. Contact your support personnel.
ERROR_INDEX_ABSENT 1611 The component qualifier not present.
ERROR_INSTALL_SOURCE_ABSENT 1612 The installation source for this product is not available. Verify that the source exists and that you can access it.
ERROR_INSTALL_PACKAGE_VERSION 1613 This installation package cannot be installed by the Windows Installer service. You must install a Windows service pack that contains a newer version of the Windows Installer service.
ERROR_PRODUCT_UNINSTALLED 1614 The product is uninstalled.
ERROR_BAD_QUERY_SYNTAX 1615 The SQL query syntax is invalid or unsupported.
ERROR_INVALID_FIELD 1616 The record field does not exist.
ERROR_INSTALL_ALREADY_RUNNING 1618 Another installation is already in progress. Complete that installation before proceeding with this install.For information about the mutex, see _MSIExecute Mutex.
ERROR_INSTALL_PACKAGE_OPEN_FAILED 1619 This installation package could not be opened. Verify that the package exists and is accessible, or contact the application vendor to verify that this is a valid Windows Installer package.
ERROR_INSTALL_PACKAGE_INVALID 1620 This installation package could not be opened. Contact the application vendor to verify that this is a valid Windows Installer package.
ERROR_INSTALL_UI_FAILURE 1621 There was an error starting the Windows Installer service user interface. Contact your support personnel.
ERROR_INSTALL_LOG_FAILURE 1622 There was an error opening installation log file. Verify that the specified log file location exists and is writable.
ERROR_INSTALL_LANGUAGE_UNSUPPORTED 1623 This language of this installation package is not supported by your system.
ERROR_INSTALL_TRANSFORM_FAILURE 1624 There was an error applying transforms. Verify that the specified transform paths are valid.
ERROR_INSTALL_PACKAGE_REJECTED 1625 This installation is forbidden by system policy. Contact your system administrator.
ERROR_FUNCTION_NOT_CALLED 1626 The function could not be executed.
ERROR_FUNCTION_FAILED 1627 The function failed during execution.
ERROR_INVALID_TABLE 1628 An invalid or unknown table was specified.
ERROR_DATATYPE_MISMATCH 1629 The data supplied is the wrong type.
ERROR_UNSUPPORTED_TYPE 1630 Data of this type is not supported.
ERROR_CREATE_FAILED 1631 The Windows Installer service failed to start. Contact your support personnel.
ERROR_INSTALL_TEMP_UNWRITABLE 1632 The Temp folder is either full or inaccessible. Verify that the Temp folder exists and that you can write to it.
ERROR_INSTALL_PLATFORM_UNSUPPORTED 1633 This installation package is not supported on this platform. Contact your application vendor.
ERROR_INSTALL_NOTUSED 1634 Component is not used on this machine.
ERROR_PATCH_PACKAGE_OPEN_FAILED 1635 This patch package could not be opened. Verify that the patch package exists and is accessible, or contact the application vendor to verify that this is a valid Windows Installer patch package.
ERROR_PATCH_PACKAGE_INVALID 1636 This patch package could not be opened. Contact the application vendor to verify that this is a valid Windows Installer patch package.
ERROR_PATCH_PACKAGE_UNSUPPORTED 1637 This patch package cannot be processed by the Windows Installer service. You must install a Windows service pack that contains a newer version of the Windows Installer service.
ERROR_PRODUCT_VERSION 1638 Another version of this product is already installed. Installation of this version cannot continue. To configure or remove the existing version of this product, use Add/Remove Programs in Control Panel.
ERROR_INVALID_COMMAND_LINE 1639 Invalid command line argument. Consult the Windows Installer SDK for detailed command-line help.
ERROR_INSTALL_REMOTE_DISALLOWED 1640 The current user is not permitted to perform installations from a client session of a server running the Terminal Server role service.
ERROR_SUCCESS_REBOOT_INITIATED 1641 The installer has initiated a restart. This message is indicative of a success.
ERROR_PATCH_TARGET_NOT_FOUND 1642 The installer cannot install the upgrade patch because the program being upgraded may be missing or the upgrade patch updates a different version of the program. Verify that the program to be upgraded exists on your computer and that you have the correct upgrade patch.
ERROR_PATCH_PACKAGE_REJECTED 1643 The patch package is not permitted by system policy.
ERROR_INSTALL_TRANSFORM_REJECTED 1644 One or more customizations are not permitted by system policy.
ERROR_INSTALL_REMOTE_PROHIBITED 1645 Windows Installer does not permit installation from a Remote Desktop Connection.
ERROR_PATCH_REMOVAL_UNSUPPORTED 1646 The patch package is not a removable patch package. Available beginning with Windows Installer version 3.0.
ERROR_UNKNOWN_PATCH 1647 The patch is not applied to this product. Available beginning with Windows Installer version 3.0.
ERROR_PATCH_NO_SEQUENCE 1648 No valid sequence could be found for the set of patches. Available beginning with Windows Installer version 3.0.
ERROR_PATCH_REMOVAL_DISALLOWED 1649 Patch removal was disallowed by policy. Available beginning with Windows Installer version 3.0.
ERROR_INVALID_PATCH_XML 1650 The XML patch data is invalid. Available beginning with Windows Installer version 3.0.
ERROR_PATCH_MANAGED_ADVERTISED_PRODUCT 1651 Administrative user failed to apply patch for a per-user managed or a per-machine application that is in advertise state. Available beginning with Windows Installer version 3.0.
ERROR_INSTALL_SERVICE_SAFEBOOT 1652 Windows Installer is not accessible when the computer is in Safe Mode. Exit Safe Mode and try again or try using System Restore to return your computer to a previous state. Available beginning with Windows Installer version 4.0.
ERROR_ROLLBACK_DISABLED 1653 Could not perform a multiple-package transaction because rollback has been disabled. Multiple-Package Installations cannot run if rollback is disabled. Available beginning with Windows Installer version 4.5.
ERROR_INSTALL_REJECTED 1654 The app that you are trying to run is not supported on this version of Windows. A Windows Installer package, patch, or transform that has not been signed by Microsoft cannot be installed on an ARM computer.
ERROR_SUCCESS_REBOOT_REQUIRED 3010 A restart is required to complete the install. This message is indicative of a success. This does not include installs where the ForceReboot action is run.

Note: The error codes ‘ERROR_SUCCESS’ (0), ‘ERROR_SUCCESS_REBOOT_INITIATED’ (1641), and ‘ERROR_SUCCESS_REBOOT_REQUIRED’ (3010) are indicative of success. If ‘ERROR_SUCCESS_REBOOT_REQUIRED’ (3010) is returned, the installation completed successfully but a reboot is required to complete the installation operation

Source: Microsoft

ICACLS examples (CMD)

Here are a few examples of the most common Icacls commands, that I use in Command Shell, to give further access.

icacls.exe "[folder]" /grant *S-1-5-32-545:(OI)(CI)F
icacls.exe "[folder]" /grant *S-1-5-32-545:(OI)(CI)M
icacls.exe "[path][file]" /grant *S-1-5-32-545:F
icacls.exe "[path][file]" /grant *S-1-5-32-545:M

For a complete list of ‘Well-known security identifiers’ (SIDs) please visit Microsoft.

Note: Icacls are build into Windows Vista, Windows 7 & Windows 8 and equivalent Windows Servers

SetACL examples (CMD)

Here are a few examples of the most common SetACL commands, that I use in Command Shell, to give further access.

SetACL.exe -on "[folder][file]" -ot file -actn ace -ace "n:S-1-5-32-545;p:change;s:y"
SetACL.exe -on "[folder][file]" -ot file -actn clear -clr "dacl,sacl"
SetACL.exe -on "[key]" -ot reg -actn ace -ace "n:S-1-5-32-545;p:full;s:y"
SetACL.exe -on "[service]" -ot svr -actn ace -ace "n:S-1-5-32-545;p:start_stop;s:y"

For a complete list of ‘Well-known security identifiers’ (SIDs) please visit Microsoft.