简体   繁体   English

如何计算正在运行的EC2实例?

[英]How can I count running EC2 Instances?

I'm looking for a very basic script to count the number of running EC2 instances at AWS using PowerShell. 我正在寻找一个非常基本的脚本来计算使用PowerShell在AWS上运行的EC2实例的数量。 I have found several methods but for some reason when I try them, I do not get the results I expect. 我找到了几种方法,但是由于某种原因,当我尝试它们时,我没有得到预期的结果。

The closest I have is this: 我最近的是:

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

which returns: 返回:

stopped
running
stopped
stopped
running

(the list goes on for about 80 instances) (该列表持续约80个实例)

I wish to have a response that counts those which are running. 我希望得到一个包含正在运行的响应的响应。

I'm not sure about others, but I prefer to explicitly assign my ec2 filters to variables, and then list them when calling something like Get-EC2Instance . 我不确定其他对象,但是我更愿意将ec2过滤器明确分配给变量,然后在调用诸如Get-EC2Instance类的内容时将其Get-EC2Instance This makes it easier to work with filters if you need to to filter on multiple conditions. 如果您需要在多个条件下进行过滤,这使得使用过滤器更加容易。

Here's a working example of what you're after, where I have 6 running instances: 这是您要执行的操作示例,其中有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

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

From this it looks like the following would work (I'm not sure about the filter syntax): 由此看来,以下方法可以工作(我不确定过滤器语法):

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

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

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