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
不要相信GET-成员除非你使用表单“get-member -inputObject $ objectName”。如果您有一个DateTimes集合并将其传递给get-member(即$ colDateTimes | get-member),它将报告DateTimes。事实上,错误提到'System.Object []'表明你正在处理一个数组/集合。 – andyb
当计算两个日期时间之间的差异时,我通常使用“($ EndTime - $ StartTime).TotalHours”形式,这更简单,然后声明新的TimeSpan对象。 – andyb