Avatar of snyderkv
snyderkv

asked on 

Script to detect restart and reboot automatically

EE,

I copied a couple powershell scripts online, but didn't work as usual. Another one was able to detect reboot pending but was not able to perform a reboot (shown below). So I just used it for the "pending reboot" and then created a list of servers out of that and used psshutdown -r @file.txt or For /f %%a in (servers.txt) do cmd /c shutdown -r -t 00

My question is if someone can add the piece that will force logoff even if users are logged on (see error I receive below) or just output the needs reboot portion into servers.txt so I can use it with psshutdown?

Here is the code

Open in new window

# Filename:  CheckForPendingReboot.ps1
# Description: Imports a list of computers from a text file and then checks each of the
#    computers for the RebootPending registry key. If the key is present,
#    the script restarts the computer upon confirmation from the user.
# Assumes the existence of a file called 'Servers.txt' in the same directory, populated with
# the NETBIOS names of a list of computers, each on a new line.
 

Open in new window

$computernames = gc Servers.txt

 foreach ($computername in $computernames)
 {
 $baseKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey("LocalMachine",$computername)
 $key = $baseKey.OpenSubKey("Software\Microsoft\Windows\CurrentVersion\Component Based Servicing\")
 $subkeys = $key.GetSubKeyNames()
 $key.Close()
 $baseKey.Close()

 If ($subkeys | Where {$_ -eq "RebootPending"})
 {
  Write-Host "There is a pending reboot for" $computername
  Restart-Computer -ComputerName $computername -confirm
 }
 Else
 {
  Write-Host "No reboot is pending for" $computername
 }
}

Open in new window

Here are the errors

Open in new window

"The system shutdown cannot be initiated because there are other users logged onto the computer"
PowershellScripting LanguagesVB ScriptShell Scripting

Avatar of undefined
Last Comment
snyderkv

8/22/2022 - Mon