Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell - Reboot and Continue Script

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!

like image 211
PnP Avatar asked Mar 01 '13 21:03

PnP


People also ask

How do I reboot from PowerShell?

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.

How do I continue a PowerShell script on the next line?

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.

Does closing PowerShell stop script?

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.


1 Answers

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.

like image 117
Goyuix Avatar answered Sep 18 '22 11:09

Goyuix