How can I run multiple PowerShell commands with restarts in userdata?

Viewed 1956

I am looking to spin up a Domain Controller in AWS using Terraform. I've tried passing all commands through userdata, but I just can't find a way to get the commands run after a reboot.

Here is my userdata:

    workflow Rename-And-Continue {
    Rename-Computer -NewName "HACKDC" -Force -Passthru
    Restart-Computer -Wait

    Install-WindowsFeature AD-Domain-Services, rsat-adds -IncludeAllSubFeature
    Install-ADDSForest -DomainName hackdc -SafeModeAdministratorPassword (ConvertTo-SecureString "SOMEPASSWORD" -AsPlainText -Force) -DomainMode Win2012R2 -DomainNetbiosName HACKDC -ForestMode Win2012R2 -Confirm:$false -Force
    Restart-Service NetLogon -EA 0
    Get-Service -Name ADWS; while($s.Status -ne "Running") {Start-Service ADWS; Start-Sleep 3};

}

$AtStartup = New-JobTrigger -AtStartup
Register-ScheduledJob -Name testWorkflow -Trigger $AtStartup -ScriptBlock {Import-Module PSWorkflow; Get-Job testWorkflow -State Suspended | Resume-Job};
Rename-And-Continue -AsJob -JobName testWorkflow

The main question here is what can be done to ensure that the workflow properly runs, so that I can set up the environment even if multiple restarts are required (yes I know the above isn't every step for properly configuring a DC, just a snippet)

1 Answers

Your current script only waits for the computer to restart.

-Wait <SwitchParameter>
        Indicates that this cmdlet suppresses the Windows PowerShell prompt and blocks the pipeline 
        until all of the computers have restarted. You can use this parameter in a script to restart
        computers and then continue to process when the restart is finished.

In order to continue running the script, you may want to use the following.

# This will restart the computer. Then delay 2 seconds. 
# Then wait for PowerShell to become available again. 
# It will also timeout after 300 seconds (5 mins).
Restart-Computer -Wait -For PowerShell -Timeout 300 -Delay 2

For more information just use the Get-Help cmdlet with the -Examples flag. The specific example would be the one below.

PS C:\>Restart-Computer -ComputerName "Server01" -Wait -For PowerShell -Timeout 300 -Delay 2

    This command restarts the Server01 remote computer and then waits up to 5 minutes (300 seconds) 
    for Windows PowerShell to be available on the restarted computer before it continues.
Related