【问题标题】:How can I run multiple PowerShell commands with restarts in userdata?如何在用户数据中运行多个 PowerShell 命令并重新启动?
【发布时间】:2019-11-11 12:32:24
【问题描述】:

我希望使用 Terraform 在 AWS 中启动域控制器。我已经尝试通过 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

这里的主要问题是可以做些什么来确保工作流正常运行,这样即使需要多次重新启动,我也可以设置环境(是的,我知道上述并不是正确配置 DC 的每个步骤, 只是一个 sn-p)

【问题讨论】:

  • 您会反对设置 Powershell DSC Pull 服务器吗?我认为这将是最干净和最可扩展的解决方案。但是,我认为可以使用单个脚本来完成,请参阅deploymentmechanic.wordpress.com/2017/04/15/…,它在注册表中设置运行计数并使用 switch() 来执行每次重启所需的阶段。
  • 这可能会奏效。希望能够仅利用 Terraform 和 Userdata 的组合,但看起来不太可能
  • AWS 执行的用户数据只是在第一次运行时。从技术上讲,Linux 系统上的用户数据 (cloud-init) 下的底层内容允许在每次重新启动时进行操作,但 AWS 用户数据不会填充该部分,这在 Linux 上对您没有帮助。如果这是一个 Linux 系统,那么我会将命令作为启用的一次性服务,然后在每次启动时运行,但我不知道 Windows 中的等价物是什么。
  • 一种破解方法是让它在 Windows 中创建计划任务,并设置为在启动时运行。但是,与该计划任务相关联的脚本需要逻辑来确保它不会重复某个步骤(可能是系统上的某个日志文件写入了它执行的“最后一步”。

标签: amazon-web-services powershell active-directory terraform


【解决方案1】:

您当前的脚本只等待计算机重新启动。

-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.

为了继续运行脚本,您可能需要使用以下内容。

# 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

有关更多信息,只需使用带有 -Examples 标志的 Get-Help cmdlet。具体示例如下。

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.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-11
    • 2018-12-12
    • 1970-01-01
    • 2018-04-26
    • 1970-01-01
    • 1970-01-01
    • 2019-05-09
    • 1970-01-01
    相关资源
    最近更新 更多