繁体   English   中英

使用AWS Powershell工具启动/停止AWS EC2实例

[英]Starting/Stopping AWS EC2 Instances using AWS Powershell Tools

我正在尝试编写两个单独的脚本。 一个脚本确定要停止的EC2实例,然后将其启动并将其启动内容记录到文本文件中。

第二个脚本将读取文本文件并停止这些实例。 为了调试/简化起见,我首先将两个脚本合并为一个脚本。

这是我的脚本:

$Instances = (Get-EC2Instance).instances
$start_instances = @()
$Instances | foreach { 
    $state = Get-EC2InstanceStatus -InstanceId $_.InstanceId  -IncludeAllInstance $true 
    $state = $state.InstanceState.Name

    if ($state -eq "stopped"){
        $start_instances += $_.InstanceId
    }
} 
[System.IO.File]::WriteAllText("C:\users\myusername\desktop\so.csv", $($start_instances  -join ','))

$shutdown_instances = [System.IO.File]::ReadAllText("C:\users\myusername\desktop\so.csv")

Write-Host "Press any key to continue ..."
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")

Stop-EC2Instance -Instance $shutdown_instances

启动并记录正在运行的实例可以正常工作。 它正在停止的实例失败了。

我收到以下错误:

Stop-EC2Instance : Invalid id: "i-99edd755,i-8d647f58"
At C:\users\myusername\Desktop\aws-test.ps1:28 char:1
+ Stop-EC2Instance -Instance $shutdown_instances
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Stop-EC2Instance], AmazonEC2Exception
    + FullyQualifiedErrorId : Amazon.EC2.AmazonEC2Exception,Amazon.PowerShell.Cmdlets.EC2.StopEC2InstanceCmdl

这些实例ID确实有效,因此我无法弄清楚其抱怨的原因。 我正在通过输出文件将实例ID写入文件,并通过get-content获得它,但这似乎引起了另一个错误。

我假设问题出在我将其从文本文件中拉出后与数据格式有关。

编辑,因此我将脚本更改为:

 $start_instances = $start_instances | Select-Object @{Name='Name';Expression={$_}}
 $start_instances | Export-Csv -Delimiter ',' -NoTypeInformation -path C:\temp\instances.csv

 $stop_instances = @(Import-Csv -path C:\temp\instances.csv)

 $stop_instances | Stop-EC2Instance

但是仍然出现错误:

Stop-EC2Instance : No instances specified
At C:\temp\aws-test.ps1:22 char:19
+ $stop_instances | Stop-EC2Instance
+                   ~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Stop-EC2Instance], AmazonEC2Exception
    + FullyQualifiedErrorId : Amazon.EC2.AmazonEC2Exception,Amazon.PowerShell.Cmdlets.EC2.StopEC2InstanceCmdlet

我也尝试过:

Stop-EC2Instance -InstanceID $stop_instances

但这也死了:

Stop-EC2Instance : No instances specified
At C:\temp\aws-test.ps1:22 char:1
+ Stop-EC2Instance -InstanceId $stop_instances
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Stop-EC2Instance], AmazonEC2Exception
    + FullyQualifiedErrorId : Amazon.EC2.AmazonEC2Exception,Amazon.PowerShell.Cmdlets.EC2.StopEC2InstanceCmdlet

InstanceId参数需要数组。

您可以先声明一个空数组

$EC2Instance =@()

然后使用Import-CSV并将其通过管道传递给空数组,并附上csv中的每个值

Import-CSV C:\Temp\Instance.csv | Foreach-Object {$EC2Instance += $_.InstanceId}

echo $EC2Instance

$ EC2instance现在将在数组中具有所需的实例ID

然后您可以在命令中使用它

Stop-EC2instance -InstanceId $EC2instance

这对我有用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM