I'm looking for a way to continue a Powershell script from where it left off after calling a reboot in the script. For example, I am building a DC via Powershell automation, and after renaming the PC to TESTDC01, need to reboot, but after the reboot, continue with the script to go on to dcpromo etc.
Is this possible?
Cheers!
Shutdown /r command-line is used to restart/reboot local or a remote computer using a command prompt. Restart-Computer cmdlet in PowerShell is used to reboot local or remote computers. You can use the -force parameter to forcefully reboot the computer.
Backtick (`) character is the PowerShell line continuation character. It ensures the PowerShell script continues to a new line. To use line continuation character in PowerShell, type space at the end of code, use backtick ` and press enters to continue to new line.
The PowerShell console will immediately close. This keyword can also exit a script rather than the console session. Including the exit keyword in a script and exit terminates only the script and not the entire console session from where the script runs.
There is a great article on TechNet from the Hey, Scripting Guy series that goes over a situation very similar to what you are describing: Renaming a computer and resuming the script after reboot. The magic is to use the new workflows that are part of version 3:
workflow Rename-And-Reboot { param ([string]$Name) Rename-Computer -NewName $Name -Force -Passthru Restart-Computer -Wait Do-MoreStuff }
Once the workflow has been declared (you don't assign it to a variable), you can call it as though it were a regular cmdlet. The real magic is the -Wait
parameter on the Restart-Computer cmdlet.
Rename-And-Reboot PowerShellWorkflows
Source: https://devblogs.microsoft.com/scripting/powershell-workflows-restarting-the-computer/
If PowerShell v3 or later isn't an available choice, you could break your existing script into multiple smaller scripts and have a master script that runs at startup, checks some saved state somewhere (file, registry, etc.), then starts executing a new script to continue on where appropriate. Something like:
$state = Get-MyCoolPersistedState switch ($state) { "Stage1" { . \Path\To\Stage1.ps1 ; break } "Stage2" { . \Path\To\Stage2.ps1 ; break } "Stage3" { . \Path\To\Stage3.ps1 ; break } default { "Uh, something unexpected happened" } }
Just be sure to remember to set your state appropriately as you move through your smaller scripts.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With