Powershell - 重启并继续脚本 [英] Powershell - Reboot and Continue Script

查看:54
本文介绍了Powershell - 重启并继续脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这可能吗?

干杯!

推荐答案

您好,脚本专家系列在 TechNet 上有一篇很棒的文章,其中讨论了与您所描述的情况非常相似的情况:重命名计算机并恢复重启后的脚本.神奇的是使用版本 3 中的新工作流程:

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
}

一旦声明了工作流(您没有将其分配给变量),您就可以像调用常规 cmdlet 一样调用它.真正的魔法是 Restart-Computer cmdlet 上的 -Wait 参数.

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

来源:https://devblogs.microsoft.com/脚本/powershell-workflows-restarting-the-computer/

如果 PowerShell v3 或更高版本不是可用的选择,您可以将现有脚本分解为多个较小的脚本,并拥有一个在启动时运行的主脚本,检查某处保存的状态(文件、注册表等),然后开始执行新脚本以继续执行适当的操作.类似的东西:

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.

这篇关于Powershell - 重启并继续脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆