2

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

我最接近的是:

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

返回:

stopped
running
stopped
stopped
running

(这个列表持续了大约 80 个实例)

我希望有一个计算那些正在运行的响应。

4

2 回答 2

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
于 2014-12-01T19:59:06.220 回答
0

使用单独的计数器计算所有实例的总数、运行和停止的实例:

(Get-EC2Instance).Instances | group InstanceType | select Name, 
@{n='Total';e={$_.Count }}, @{n='Running';e={($_.Group | ? { $_.state.Name - 
eq "running" }).Count }}, @{n='Stopped';e={($_.Group | ? { $_.state.Name -eq 
"stopped" }).Count }}

有关更多示例,请参阅我的PowerShell one-liners 备忘单

于 2021-10-28T08:49:39.287 回答