1

这应该是针对Amazon EC2中的虚拟机的查询,它按实例ID和LaunchTime列出实例(当它启动时) - 我想计算另一列LaunchTime - 当前日期/时间以获得称为HoursSinceBoot的“正常运行时间”统计信息。以小时为单位计算时间差

#get instances 
$instances = foreach($i in (get-ec2instance)) {$i.RunningInstance | Select-Object InstanceId,LaunchTime} 
$instances | Add-Member -type NoteProperty -name HoursSinceBoot -value (Foreach-object -inputobject  $instances {New-TimeSpan -End (get-date) -Start $_.LaunchTime} | select -expandproperty hours) 
$instances 

这是错误我得到的错误如下,这似乎表明Launchtime不是一个日期时间类型,果然,当我运行一个get成员可以肯定的是废话。现在我知道如果我运行$ [0] .LaunchTime这段代码可以正常工作,但由于某种原因,只需使用$变量,这一切都会变成地狱。我已经尝试了一些日期时间转换技术,如[日期时间],但他们有类似的错误“无法转换为键入日期时间”的后果。

New-TimeSpan : Cannot convert 'System.Object[]' to the type 'System.DateTime' required by parameter 'Start'. Specified method is not supported. 
At C:\xxx\powershell\aws-watchdog.ps1:3 char:149 
+ ... t-date) -Start $_.LaunchTime} | select -expandproperty hours) 
+     ~~~~~~~~~~~~~ 
    + CategoryInfo   : InvalidArgument: (:) [New-TimeSpan], ParameterBindingException 
    + FullyQualifiedErrorId : CannotConvertArgument,Microsoft.PowerShell.Commands.NewTimeSpanCommand 
+0

不要相信GET-成员除非你使用表单“get-member -inputObject $ objectName”。如果您有一个DateTimes集合并将其传递给get-member(即$ colDateTimes | get-member),它将报告DateTimes。事实上,错误提到'System.Object []'表明你正在处理一个数组/集合。 – andyb

+2

当计算两个日期时间之间的差异时,我通常使用“($ EndTime - $ StartTime).TotalHours”形式,这更简单,然后声明新的TimeSpan对象。 – andyb

回答

1

您可能会更好地计算新的HoursSinceBoot属性作为您的选择的一部分。

下面是一个例子:

PS C:\> $launchData = Get-EC2Instance | ` 
         % { $_.RunningInstance } | ` 
         Select-Object InstanceId, LaunchTime, @{Name='HoursSinceBoot'; Expression={ ((Get-Date)-$_.LaunchTime).TotalHours } } 
PS C:\> $launchData | Format-Table -AutoSize 

InstanceId LaunchTime    HoursSinceBoot 
---------- ----------    -------------- 
i-abcd1234 6/11/2014 11:14:39 AM 1061.46170712353 
i-efgh5678 7/11/2014 11:02:24 AM 341.665873790194 

这里发生了什么:

  • Get-EC2Instance通过管道被输送到的foreach对象(由百分号化名),其拉RunningInstance财产关每个EC2预订目的。
  • 我们将每个RunningInstance管道传递给Select-Object以选择InstanceId和LaunchTime,然后生成一个名为HoursSinceBoot的新属性。
  • 表达式中有括号作为操作顺序的问题。它允许我们在从LaunchTime减去之前评估当前日期,并在尝试从生成的DateTime中提取TotalHours属性之前减去该值。
  • 我结合@andyb的计算DateTime差异的建议。

而且,对于琐事的缘故......您可以通过EC2实例的说明标签下检查仔细检查AWS控制台上该值:

An image of a snippet of the AWS console, describing the launch time of one of my EC2 instances.