2016-11-15 27 views
0

我有一個對象,需要將一個列從Unix時間轉換爲「人類」時間。我的對象如下所示:修改數組中的unix時間變量

PS C:\Windows\system32\WindowsPowerShell\v1.0> $AllAgents.agents[0..2] | Format-Table 

last_scanned ip    distro  platform name   uuid             id 
------------ --    ------  -------- ----   ----             -- 
1460167223 192.168.118.101 win-x86-64 WINDOWS COMPUTER-1  648f8f4f-8afa-029d-424f-fb27a8e345f8e2fdef184343058e 101 
1460167223 192.168.118.145 win-x86-64 WINDOWS COMPUTER-2  0a33a831-fa47-1fdc-2c21-2a079c728a88bcf6186e275a9135 152 
1460167223 192.168.118.26 win-x86-64 WINDOWS COMPUTER-3  738c0d3a-d2d5-447c-c671-b248180c3b3f75efb734be3d547d 359 

「last_scanned」列是我需要更改的列。我有以下代碼:

$Origin = New-Object -Type DateTime -ArgumentList 1970, 1, 1, 0, 0, 0, 0 
$AllAgents.agents.last_scanned = $AllAgents.agents.last_scanned | ForEach-Object { 
    $_ = $Origin.AddSeconds($_) 
    $_ 
} 

執行以下錯誤這個循環的結果:

The property 'last_scanned' cannot be found on this object. Verify that the property exists and can be set. 
At U:\Powershell\Scripts\Nessus API - Get All Agents From a Group.ps1:55 char:1 
+ $AllAgents.agents.last_scanned = $AllAgents.agents.last_scanned | For ... 
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
    + CategoryInfo   : InvalidOperation: (:) [], RuntimeException 
    + FullyQualifiedErrorId : PropertyAssignmentException 

我不知道爲什麼PowerShell中認爲last_scanned屬性不存在,因爲它是明顯存在的。我怎樣才能將last_scanned屬性修改爲更具可讀性的日期並將該值放回到對象中?

回答

1

您使用的是什麼版本的PowerShell?看起來你有一個.agents屬性下的對象數組,然後每個都有自己的.last_scanned屬性,版本3+允許你像這樣訪問數組成員的子屬性,但版本2不屬於這個屬性,這是否適合你?

$Origin = New-Object -Type DateTime -ArgumentList 1970, 1, 1, 0, 0, 0, 0 
$AllAgents.agents = $AllAgents.agents | ForEach-Object { 
    $_.LastScanned = $Origin.AddSeconds($_.LastScanned) 
    $_ 
} 
+0

我正在使用PS 5.0。我現在正在嘗試你的建議,如果有效,我會告訴你。 – Tchotchke

+0

做到了!你和我基本上做了同樣的事情,但你比我高一級(AllAgents.agents,而我在AllAgents.agents.last_scanned)。你能解釋一下爲什麼你的方式有效嗎,但我沒有? – Tchotchke

+1

好吧我認爲這只是早期版本的限制,但可能有其他原因,它不適用於這些對象,基本上你試圖訪問'$ AllAgents.agents'的'.last_scanned'屬性,但是'$ AllAgents.agents '是一個數組,並沒有'.agents'屬性。做你正在做的事情實際上與大多數PowerShell對象一起工作,所以我猜測你是在一個較舊的版本,但如果你使用5,那麼我只能假設它是奇怪的$ AllAgents對象,但我不知道什麼。希望有所幫助。 –