How can I count running EC2 Instances?

余生长醉 提交于 2019-12-12 23:57:26

问题


I'm looking for a very basic script to count the number of running EC2 instances at AWS using PowerShell. 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)

I wish to have a response that counts those which are running.


回答1:


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

# 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



回答2:


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


来源:https://stackoverflow.com/questions/26740777/how-can-i-count-running-ec2-instances

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!