【问题标题】:How to reboot a azure vm from powershell script and continue the remaining steps如何从 powershell 脚本重新启动 azure vm 并继续其余步骤
【发布时间】:2021-03-03 15:17:01
【问题描述】:

我有一个天蓝色的虚拟机。我正在编写一个执行两个 .bat 文件的 powershell 脚本,之后它必须重新启动 azure VM,之后它必须继续执行剩余的 .bat 文件。

这是下面的脚本

第一步:set-location -path C:/temp

第二步:start-process cmd.exe /c "abc.bat" -wait

第三步:start-process cmd.exe /c "123.bat" -wait

第四步:restart-computer -Force

第五步:start-process cmd.exe /c "prod.bat" -wait

第六步:start-process cmd.exe /c "dev.bat" -wait

我通过下面的命令远程执行这个脚本

PS C:\> Invoke-AzVMRunCommand -ResourceGroupName 'rgname' -VMName 'vmname' -CommandId 'RunPowerShellScript' -ScriptPath '/Users/username/sample.ps1'

运行上述命令后,它的执行正常到“第 4 步”。之后不再继续执行其余步骤

你能帮我解决这个问题吗?

【问题讨论】:

    标签: azure powershell automation


    【解决方案1】:

    我可以想到两种方法,并在下面详细介绍它们:

    方法一:

    使用注册表键RUNONCE - 可用于指定系统将执行一次然后删除的命令。

    更多信息here

    远程运行时会有细微的修改。

    当您使用 Invoke-AzVMRunCommand 时,初始命令必须将 2 个脚本文件复制到远程 VM 中的临时位置并启动第一个脚本(这包含步骤 1-3)

    在第 4 步之前 - 您将在 RUNONCE 下创建一个注册表项:

    HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunOnce
    
    set-location HKLM:\Software\Microsoft\Windows\CurrentVersion\RunOnce
    new-itemproperty . MyKey -propertytype String -value "Powershell c:\temp\script2.ps1"
    

    或者您也可以直接在 RunOnce 键下添加 .bat 文件。

    在RUNONCE键下的文件在登录后被执行,执行后被删除。

    方法二:

    您可以参考以下创建工作流的文章,并创建 ScheduledTask 以恢复暂停的工作流。

    https://devblogs.microsoft.com/scripting/powershell-workflows-restarting-the-computer/#automatic-restart-of-workflow

    workflow test-restart {
    
     #STEPS 1-3
    
     Restart-Computer -Wait
    
     #STEPS 5 - 6
    } 
    

    调度:

    $act = New-ScheduledTaskAction -Execute $pstart -Argument $actionscript
    $trig = New-ScheduledTaskTrigger -AtLogOn
    

    注意: 不强制使用示例中的工作流。您可以编写自己的逻辑,以便在重新触发后从您离开的点恢复 - 通过持久化步骤数据。

    此方法的关键是创建一个计划任务,该任务被触发以在重新启动后自动继续执行脚本。

    即使在这种情况下,也可能需要将脚本本地复制到机器上。

    【讨论】:

    • 谢谢 sathya 你的意思是我必须创建名为 c:\temp\script2.ps1 的单独脚本,其中包含步骤 5 到 6 并放置在初始脚本中。所以我的脚本最终看起来像这样? Step1:set-location -path C:/temp Step2:start-process cmd.exe /c "abc.bat" -wait Step3:start-process cmd.exe /c "123.bat" -wait step4:set-location HKLM:\Software\Microsoft\Windows\CurrentVersion\RunOnce new-itemproperty 。 MyKey -propertytype String -value "Powershell c:\temp\script2.ps1" 如有错误请指正
    • 嗨,sathya,我需要在第 4 步之后添加命令“restart-computer”
    • 是的,一旦您设置了注册表项,您就可以启动重新启动计算机命令
    • @nikhileshwary - 以上步骤对您有用吗?另外,如果有帮助,请考虑接受答案作为解决方案。
    • 嗨,Sathya,它不工作。我怀疑这个脚本路径“Powershell c:\temp\script2.ps1”存在于本地计算机中。可能是这个路径在本地计算机中而不是在VM中是它不起作用的原因吗?
    猜你喜欢
    • 2013-02-16
    • 2014-08-21
    • 1970-01-01
    • 2021-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-15
    • 2018-06-11
    相关资源
    最近更新 更多