Powershell - Reboot and Continue Script

前端 未结 7 2047
误落风尘
误落风尘 2020-12-02 11:07

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

7条回答
  •  庸人自扰
    2020-12-02 11:51

    Needed to reboot my local computer and continue script after. Tried solution from @adaml but I just couldn't get the scheduled job (that ran after the reboot) to find the suspended workflow-job that should be resumed. Hence, it remained suspended.

    Get-Job didn't return the job no matter credentials or elevated. Another strange thing was that if I ran the workflow by marking code in Powershell ISE and ran the section with F8, the job never got suspended... Had to run the whole script with F5 or called it from somewhere else.

    To get the resume of the job working, I had to register a scheduled-Task instead of a scheduled-Job:

    workflow test-restart {
        Write-Output "Before reboot" | Out-File  C:/Log/t.txt -Append
    
        Restart-Computer -Wait
    
        Write-Output "$Now2 After reboot" | Out-File  C:/Log/t.txt -Append
    }
    
    $PSPath = "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe"
    $Args = '-NonInteractive -WindowStyle Hidden -NoLogo -NoProfile -NoExit -Command "& {Import-Module PSWorkflow ; Get-Job | Resume-Job}"'
    $Action = New-ScheduledTaskAction -Execute $PSPath -Argument $Args
    $Option = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -WakeToRun
    $Trigger = New-JobTrigger -AtStartUp -RandomDelay (New-TimeSpan -Minutes 5)
    Register-ScheduledTask -TaskName ResumeJob -Action $Action -Trigger $Trigger -Settings $Option -RunLevel Highest
    
    
    test-restart -AsJob
    

提交回复
热议问题