Eran Mor
Eran Mor

Reputation: 105

Check if a reboot is needed and continue Powershell script after reboot?

This question was asked a few times before but I could not find a solution to my scenario in any of them.

Basically I need the script to continue after it reboots if needed. It will check a few registry keys and will determine if the machine needs to be rebooted.

I tried using 'workflow' in various ways but could not get it to work successfully.

Here is the rough description of my code:

function (check-if-computer-needs-a-reboot){
    if(this and that)

    try{

    return $true
    }
    catch{}

    return $false
    }

if(check-if-computer-needs-a-reboot = $true){

Write-Host "The machine is rebooting..."
Restart-Computer -Wait -Force
Write-Host "The machine was successfully rebooted"

}

    else 

    {
    Write-Host "No pending reboot" 
    }

Hoping the wizards of Stack-overflow can help.

Any help will be greatly appreciated!!!

Upvotes: 0

Views: 2682

Answers (1)

user15261314
user15261314

Reputation: 7

To continue doing something after a reboot, you need to add a value to the Runonce registry key to specify what to do after the reboot.

Break break your script into two parts (Preboot and Postboot). Put the following at the end of Preboot.ps1:

if(check-if-computer-needs-a-reboot){
  REG ADD "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Runonce" /V "Postboot" /d "\"%~dpPostboot.ps1\" MyParameters" /t REG_SZ /f
  Write-Host "The machine is rebooting..."
  Restart-Computer -Wait -Force
}
# Fall through if reboot was not needed, so continue with part 2
Write-Host "No pending reboot... continuing"
"%~dpPostboot.ps1"

Notes:

  1. I copied this from a .bat file. In a .bat file "%~dp0" means "the drive and path that the current script is running from". The syntax in Powershell might be a little different.

  2. While Powershell can run other programs such as REG.EXE, Powershell has its own built-in HKLM: PSdrive. That should be more efficient than using REG.EXE. I leave it to you to do the conversion.

  3. In your code, you test if a Boolean value "equals" $True. This comparison is never necessary unless the value isn't really Boolean and could be something other than True or False. Just test the Boolean value itself as I've shown above.

Upvotes: 0

Related Questions