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.