How can I count running EC2 Instances?

2019-08-01 12:15发布

问题:

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