Powershell - 重启并继续脚本

PnP*_*PnP 28 powershell powershell-2.0 powershell-3.0

我正在寻找一种方法来继续在脚本中调用重启后停止的Powershell脚本.例如,我通过Powershell自动化构建DC,在将PC重命名为TESTDC01之后,需要重新启动,但在重新启动后,继续使用脚本继续执行dcpromo等.

这可能吗?

干杯!

Goy*_*uix 28

来自Hey,Scripting Guy系列的TechNet上有一篇很棒的文章介绍了与你所描述的非常相似的情况:重命名计算机并在重启后恢复脚本.神奇的是使用属于版本3的新工作流程:

workflow Rename-And-Reboot {
  param ([string]$Name)
  Rename-Computer -NewName $Name -Force -Passthru
  Restart-Computer -Wait
  Do-MoreStuff
}
Run Code Online (Sandbox Code Playgroud)

声明工作流后(不将其分配给变量),可以将其称为常规cmdlet.真正的魔力是-WaitRestart-Computer cmdlet上的参数.

Rename-And-Reboot PowerShellWorkflows
Run Code Online (Sandbox Code Playgroud)

资料来源:http://blogs.technet.com/b/heyscriptingguy/archive/2013/01/23/powershell-workflows-restarting-the-computer.aspx

如果PowerShell v3或更高版本不是可用选项,您可以将现有脚本分解为多个较小的脚本,并具有在启动时运行的主脚本,在某处检查某些已保存的状态(文件,注册表等),然后开始执行新脚本在适当的地方继续.就像是:

$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" }
}
Run Code Online (Sandbox Code Playgroud)

请务必记住在浏览较小的脚本时适当设置状态.

  • 当我尝试使用"Restart-Computer -Wait"时,我得到一个例外:"不能等待本地计算机重新启动.当指定Wait参数时,将忽略本地计算机." (2认同)
  • 文章可重新启动性的真正诀窍,尤其是用于本地执行时……是脚本创建了计划任务以继续执行……无论您是否使用自己的脚本,都可以执行相同的操作。 (2认同)
  • 我认为“restart-computer -wait”仅适用于远程计算机。 (2认同)

ada*_*aml 15

上面的答案是正确的,但它只适用于PowerShell脚本的远程执行.根据Windows Web门户网站,在本地计算机重新启动后从本地运行的脚本恢复的方式恢复的方式如下:

workflow Resume_Workflow
{
    .....
    Rename-Computer -NewName some_name -Force -Passthru
    Restart-Computer -Wait
    # Do some stuff
    .....
}
# Create the scheduled job properties
$options = New-ScheduledJobOption -RunElevated -ContinueIfGoingOnBattery -StartIfOnBattery
$secpasswd = ConvertTo-SecureString "Aa123456!" -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential ("WELCOME\Administrator", $secpasswd)
$AtStartup = New-JobTrigger -AtStartup

# Register the scheduled job
Register-ScheduledJob -Name Resume_Workflow_Job -Trigger $AtStartup -ScriptBlock ({[System.Management.Automation.Remoting.PSSessionConfigurationData]::IsServerManager = $true; Import-Module PSWorkflow; Resume-Job -Name new_resume_workflow_job -Wait}) -ScheduledJobOption $options
# Execute the workflow as a new job
Resume_Workflow -AsJob -JobName new_resume_workflow_job
Run Code Online (Sandbox Code Playgroud)

请注意,[System.Management.Automation.Remoting.PSSessionConfigurationData]::IsServerManager仅当工作流操作要在重新启动后在本地执行时,才应将该标志设置为true.

  • 使用的凭证是什么?我测试了你的脚本,我可以看到创建的作业,但是在重启后它处于挂起状态:Get-Job | 格式表-AutoSize (2认同)

E.V*_*.L. 5

查看带有工作流程的PS 3.0.我还没有与他们合作,但他们假设从重启恢复.