【问题标题】:How can I count running EC2 Instances?如何计算正在运行的 EC2 实例?
【发布时间】:2021-10-28 16:49:39
【问题描述】:

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

我最接近的是:

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

返回:

stopped
running
stopped
stopped
running

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

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

【问题讨论】:

  • 你试过了吗:(get-ec2instance).count?
  • 可能类似于$instancestate = get-ec2instance | where {$_.instances.state.name -eq "running"}; $count = $instancestate | measure-object | select -expandproperty count?
  • 不幸的是,上述解决方案都不起作用。第一个将计算所有实例(不仅仅是那些在问题中运行的实例)。第二个不尊重 _.instances.state.name - 由于某种原因,它再次返回所有实例(过滤器不起作用 - 它显示所有正在运行和停止的实例)。我相信这可能是 PowerShell CmdLet 中的一个错误。
  • 好的,那么我猜(get-ec2instance).instances.state.name 返回一个数组?如果是这样你可以试试(get-ec2instance).instances.state.name | where {$_ -eq "running"} 如果不是请告诉我们它返回什么类型的对象
  • 您可以通过在 $instancestate ($instancestate.gettype()) 上使用 .gettype() 来获取对象类型。这只是猜测。根据您描述的输出(请始终包括有问题的完整输出)替换 @ 987654329@ 和 $_.value 可能会起作用

标签: powershell amazon-web-services amazon-ec2 aws-powershell


【解决方案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

【讨论】:

    【解决方案2】:

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

    (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 cheat sheet。

    【讨论】:

      猜你喜欢
      • 2021-05-30
      • 2018-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-20
      • 2019-04-23
      相关资源
      最近更新 更多