简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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