使用 powershell 启动/停止 AWS 中的实例并等待

Joh*_*rad 3 .net powershell amazon-web-services

据我了解,通过 Powershell 启动和停止实例非常容易:

$awsCreds = Get-AWSAutomationCreds
Set-AWSCredentials -AccessKey $awsCreds.AccessKey -SecretKey $awsCreds.SecretKey
Set-DefaultAWSRegion -Region us-east-1

$instances = Get-EC2Instance -Filter @{name="tag:Name"; values="SERVERNAMES"} | Select -ExpandProperty Instances
$instances.InstanceId | foreach {Stop-EC2Instance $_ -ErrorAction SilentlyContinue}
Run Code Online (Sandbox Code Playgroud)

有没有一种快速而肮脏的方法,我只是没有通过 AWS Powershell Cmdlet 甚至 .NET SDK 看到它,让我可以等到操作完成。和/或更新我收集的实例对象的集合?

或者我是否坚持运行:

$instances = Get-EC2Instance -Filter @{name="tag:Name"; values="SERVERNAMES"} | Select -ExpandProperty Instances
Run Code Online (Sandbox Code Playgroud)

一遍又一遍地命令,直到状态完全改变?

Mar*_*agg 6

Sam Martin在 Github 上有一个 PowerShell 模块,其中包含一些适用于 AWS 的 PowerShell 辅助函数,您可以在此处找到: https: //github.com/Sam-Martin/AWSWindowsHelpers/

Wait-AWSWindowsHelperInstanceToStop他解决这个问题的方法可以在他的 cmdlet和cmdlet中看到Wait-AWSWindowsHelperInstanceReady,并且(正如您已经建议的那样)只是运行一个带有 start-sleep 的循环,直到实例处于您期望的状态。例如:

While((Get-EC2Instance -InstanceId $InstanceID -Region $Region).Instances[0].State.Name -ne 'stopped'){
    Write-Verbose "Waiting for instance to stop"
    Start-Sleep -s 10
}
Run Code Online (Sandbox Code Playgroud)