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