2016-04-05 31 views
0

我期待對兩個使用Import/Export-Clixml生成的變量$list$oldList進行比較。如何比較Powershell中的變量屬性?

這是我以前提出的參考問題。它包含更多細節,如果需要。

How should I store a reference variable for continued iteration in Powershell

因爲,我成功地測試了下面的腳本:

$list = Get-ChildItem C:\localApps\AutomationTest\Loading | where {$_.PSIsContainer} 
$list | Export-Clixml C:\LocalApps\AutomationTest\Loading\foldernames.xml 
$oldList = Import-Clixml C:\LocalApps\AutomationTest\Loading\foldernames.xml 
$oldList 

我的目標是到$list.LastWriteTime比作$oldList.LastWriteTime並獲得自被添加到列表中,任何新的目錄名的「 oldList「生成。這些新的目錄名稱將被處理並添加到「oldList」中......等等。

在想或許像下面的東西可以工作?

Compare-Object -ref $oldList -diff $list 
if ($list.LastWriteTime -gt $oldList.LastWriteTime} 
"Continue....(Load lastest folder names into process)" 
+0

因此,如果'$ list'中的文件夾比'$ oldList'中的對應文件更新並將其添加到'$ oldlist'中?因此,如果該文件夾是新的,那麼應該添加它 – Matt

+0

爲什麼不只是覆蓋整個列表,然後用當前最新的?你需要保留那些不再存在的舊的?我想我有點失落至於你的最終比賽是什麼。 – Matt

+0

@Matt我正在檢查新文件夾名稱的目錄。然後,我會將新的文件夾名稱加載到我的腳本變量中,以便由我的.exe處理。該腳本每天運行並檢查要加載的新文件夾。我只是想確保它不會處理重複的名稱。所以我決定將已經處理的文件夾名稱添加到oldList中。然後,我將檢查我的目錄是否有新的文件夾名稱,並且只有當它們更新時,纔會處理它們,然後處理OldList中的姓氏。 – Twdeveloper

回答

0

Compare-Object是你所要求的。只需確保您正在進行正確的後期處理。如果您只是在尋找$list中存在的更改,請在使用Where-Object進行過濾時使用正確的側面指示燈。

Compare-Object $oldList $list | Where-Object{$_.Sideindicator -eq "=>"} | Select-Object -expandProperty InputObject 

這將剛剛返回對應於沒有在$oldList存在的文件夾的Directory.Info對象。從該命令捕獲輸出是您正在做什麼來進行其他處理。

之後,只需要$list並輸出到$oldList來自的位置。除此之外並沒有多大的意義。

1

以下是對以前存在的每個文件夾項目的舊XML進行日期時間檢查的示例。它將跳過不在舊列表中的任何內容。

希望這能給你一個很好的起點。

$oldList = Import-Clixml #etc 

function Check-Against ([PsObject]$oldList, [string]$path){ 

    $currentItems = Get-ChildItem $path | ? {$_.PSIsContainer} 

    foreach ($oldItem in $oldList){ 

     $currentItem = $currentItems | ? Name -like ($oldItem.Name) 

     if ($currentItem -ne $null){ 
      $oldWriteTime = $oldItem.LastWriteTime 
      $val = $currentItem.LastWriteTime.CompareTo($oldWriteTime) 

      if ($val -gt 0){ 
       # Folder has been changed since then 
       # Do your stuff here 
      } 

      if ($val -eq 0){ 
       # Folder has not changed 
       # Do your stuff here 
      } 

      if ($val -lt 0){ 
       # Somehow the folder went back in time or was restored 
       # Do your stuff here 
      } 
     } 
    } 
}