Continuing PowerShell Scripts After Reboot

continue powershell script after reboot

Written by Alex Marin · June 7, 2024

In PowerShell scripting, ensuring that scripts continue after a reboot can be challenging, especially when managing configurations or updates that require a system reboot. There are two main strategies for local and remote execution environments to address this issue.

Let’s dive into how you can make your PowerShell scripts pick up where they left off after a reboot, whether you’re working on your own computer or handling tasks on remote machines.

Using Task Scheduler for local computers

To keep your PowerShell script running after a reboot on a local computer, use Windows Task Scheduler.

This method configures a task that starts after a restart, so you don’t need to manually restart your script.

Let’s dive into two practical examples of its implementation reboot and resume pattern with PowerShell, using the Windows Task Scheduler.

Example 1: Run a script block after reboot

In this example, we’ll create a simple PowerShell script that performs some initial actions, and then set up a scheduled task to run a script block after the system reboots.

# Initial actions
Write-Host "Performing initial actions before reboot..."
# Command to run a script block upon reboot
$scriptBlock = {
	Write-Host "This is the continuation after reboot."
}
# Convert script block to a Base64 encoded string to pass it to the scheduled task
$encodedCommand = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($scriptBlock.ToString()))
# Creating the scheduled task
$action = New-ScheduledTaskAction -Execute 'Powershell.exe' -Argument "-EncodedCommand $encodedCommand"
$trigger = New-ScheduledTaskTrigger -AtStartup
Register-ScheduledTask -Action $action -Trigger $trigger -TaskName "ContinueAfterReboot" -Description "My task to continue script execution after reboot"
# Restart the computer (uncomment in actual use)
Restart-Computer

In this scenario, the PowerShell script handles the problem by first the execution of preliminary actions— these can range from system checks, closing applications, or steps to prepare for an update. Then, that creates a scheduled task designed to run a PowerShell script block that contains the commands or continuation logic needed to finalize the system configuration after a reboot.

To achieve this, the scenario converts the PowerShell script block to a Base64 hardcoded string because the scheduled task command line does not accept script blocks directly.

When the system boots, the task starts, launching PowerShell with the coded script block as an argument, effectively resuming script execution right where you need it.

EncodedCommand in Command Prompt

EncodedCommand in Command Prompt

Example 2: Run the same or a different script based on a registry key

In the second example, the script checks for a registry key to determine if it is the first run or a continuation after a reboot.

  • If it is the first run, it performs the initial actions and plans to run again after reboot.
  • If it continues after a reboot, it skips the initial part and continues with the following actions.
# Check for the registry key to determine if this is the initial run or continuation
if (Test-Path -Path "HKCU:\Software\Test\ISRun") {
	# This is a continuation after reboot
	Write-Host "Continuing with the next part of the script..."
	# Perform the next part of the script...
	# Clean up: Remove the registry key and scheduled task if no longer needed
	Remove-Item -Path "HKCU:\Software\Test\ISRun"
	Unregister-ScheduledTask -TaskName "ContinueAfterReboot" -Confirm:$false
}
else {
	# This is the initial run
	Write-Host "Performing initial actions..."
	# Set a registry key to indicate the script has run
	New-Item -Path "HKCU:\Software\Test" -Force
	New-ItemProperty -Path "HKCU:\Software\Test" -Name "ISRun" -Value "true" -PropertyType "String" -Force
	# Schedule this script to run after reboot
	$action = New-ScheduledTaskAction -Execute 'Powershell.exe' -Argument "-File `"$PSScriptRoot\$(Split-Path -Path $MyInvocation.MyCommand.Path -Leaf)`""
	$trigger = New-ScheduledTaskTrigger -AtStartup
	Register-ScheduledTask -Action $action -Trigger $trigger -TaskName "ContinueAfterReboot" -Description "Task to rerun the script after reboot"
	# Restart the computer (uncomment in actual use)
Restart-Computer
}

This example handles a common scenario where a script needs to run in two phases, with a restart in between, with no manual intervention to restart it. The challenge is to make sure the script knows whether it is running for the first time or continuing after a reboot.

The solution is to use Windows registry as a marker or flag to track the state of script execution.

During the first run, the script performs its initial set of actions – these may include system diagnostics, pre-update tasks, or configurations that need to be applied before a reboot. It then creates a specific registry key (HKCU:\Software\Test\ISRun) to mark that the initial phase is over. Then, it plans itself (or another scenario) in is executed at the next system startup.

After the reboot, the scheduled task starts the script again, which first checks for the registry key.

If the switch is there, it knows the initialization phase is complete and moves on to subsequent tasks—post-reboot configurations, cleanup operations, or any finalization steps required to complete the task.

After completing these actions, the script removes the registry key (and the scheduled task if necessary) to clean up and prevent it from running again on future reboots.

Using computer restart for remote computer

For remote computers, it gets a little easier with Restart-Computer-Wait command. This command tells your script to wait until the computer restarts before continuing.

Here’s how to use it:

Restart-Computer -ComputerName "RemotePC1", "RemotePC2" -Wait -For PowerShell -Timeout 600 -Delay 2

MANAGEMENT reboot and continue operations for remote computers can be done using Restart the computer cmdlet, extended with Wait the parameter. This parameter stops the script from running until the specified remote computers have completed their restart process.

However, it is important to note the limitations when applying this method on the local computer.

According to Microsoft’s documentation, Wait the parameter does not apply when restarting the local machine itself. If you include both remote and local computer names in the The name of the computer parameter, the cmdlet issues a non-terminating error to the local machine while conveniently waiting for the remote machines to reboot.

This command restarts RemotePC1 and RemotePC2 and waits up to 600 seconds (10 minutes) for them to restart and continue running the script, checking every 2 seconds to see if they are back online.

CONCLUSION

Using these methods, you can automate tasks that need a restart without manual intervention.

Whether you’re deploying software updates or making system changes, these techniques ensure that your PowerShell scripts continue running smoothly after a reboot, making the process smoother and more efficient.

Written by
Check out the author's page
Alex Marin

Application Packaging and SCCM Deployment Specialist, Solution Finder, Technical Writer at Advanced Installer.

Để lại một bình luận

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *

Contact Me on Zalo
Tư Vấn Miễn Phí