如何计算运行的EC2实例?

时间:2014-11-04 16:58:48

标签: powershell amazon-web-services amazon-ec2 aws-powershell

我正在寻找一个非常基本的脚本来计算使用PowerShell在AWS上运行的EC2实例的数量。我找到了几种方法,但出于某种原因,当我尝试它们时,我得不到我期望的结果。

我最接近的是:

$instancestate = (get-ec2instance).instances.state.name
$instancestate

返回:

stopped
running
stopped
stopped
running

(该列表持续约80个实例)

我希望得到一个回复​​计算正在运行的回复。

2 个答案:

答案 0 :(得分:1)

我不确定其他人,但我更愿意明确地将我的ec2过滤器分配给变量,然后在调用Get-EC2Instance之类的内容时列出它们。如果您需要在多个条件下进行过滤,这样可以更轻松地使用过滤器。

以下是您所关注的实例,我有6个正在运行的实例:

# Create the filter 
PS C:\> $filterRunning = New-Object Amazon.EC2.Model.Filter -Property @{Name = "instance-state-name"; Value = "running"}

# Force output of Get-EC2Instance into a collection.
PS C:\> $runningInstances = @(Get-EC2Instance -Filter $filterRunning)

# Count the running instances (more literally, count the collection iterates)
PS C:\> $runningInstances.Count
6

答案 1 :(得分:-1)

http://docs.aws.amazon.com/powershell/latest/reference/Index.html?page=Get-EC2Instance.html&tocid=Get-EC2Instance

从这看起来以下内容可行(我不确定过滤器语法):

$i = Get-EC2Instance -Filter @{Name = "instance-state-name"; Value = "running"}
$i.Count
相关问题