2009-06-19 86 views
14

我需要一個PowerShell腳本,可以訪問文件的屬性並發現LastWriteTime屬性,並將其與當前日期進行比較並返回日期差異。簡單的PowerShell LastWriteTime比較

我有這樣的事情......

$writedate = Get-ItemProperty -Path $source -Name LastWriteTime 

...但我不能投的LastWriteTime到 「日期時間」 數據類型。它說,「不能轉換 「@ {LastWriteTime = ...日期...}」 到 「System.DateTime的」。

回答

18

嘗試以下。

$d = [datetime](Get-ItemProperty -Path $source -Name LastWriteTime).lastwritetime 

這是該項目物業古怪的一部分當你運行Get-ItemProperty它不返回值,而是財產你必須使用一個間接多個級別,到達值

+0

工作!謝謝! – 2009-06-19 17:07:45

+1

可行,但不必要的不​​透明,冗長和冗餘。看我的選擇。 – brianary 2011-02-28 21:49:38

2

使用

LS |。%{(獲取最新) - $ _。LastWriteTime}

它可以檢索差異。您可以用一個文件替換ls

11
(ls $source).LastWriteTime 

( 「LS」, 「目錄」 或 「GCI」 是GET-ChildItem默認的別名)。

4

(Get-Item $source).LastWriteTime是我做的首選方式。

6

我有一個例子,我想和大家分享

$File = "C:\Foo.txt" 
#retrieves the Systems current Date and Time in a DateTime Format 
$today = Get-Date 
#subtracts 12 hours from the date to ensure the file has been written to recently 
$today = $today.AddHours(-12) 
#gets the last time the $file was written in a DateTime Format 
$lastWriteTime = (Get-Item $File).LastWriteTime 

#If $File doesn't exist we will loop indefinetely until it does exist. 
# also loops until the $File that exists was written to in the last twelve hours 
while((!(Test-Path $File)) -or ($lastWriteTime -lt $today)) 
{ 
    #if a file exists then the write time is wrong so update it 
    if (Test-Path $File) 
    { 
     $lastWriteTime = (Get-Item $File).LastWriteTime 
    } 
    #Sleep for 5 minutes 
    $time = Get-Date 
    Write-Host "Sleep" $time 
    Start-Sleep -s 300; 
} 
4

我不能指責任何的答案在這裏爲OP接受了其中一人解決他們的問題。但是,我發現他們在一個方面有缺陷。將分配結果輸出到變量時,它包含許多空白行,而不僅僅是要求的答案。例如:

PS C:\brh> [datetime](Get-ItemProperty -Path .\deploy.ps1 -Name LastWriteTime).LastWriteTime 

Friday, December 12, 2014 2:33:09 PM 



PS C:\brh> 

我的代碼,簡潔性和正確性兩件事情風扇。 brianary有權利爲Roger Lipscombe提供一頂帽子,但由於結果中多餘的線條而錯過了正確性。這是我認爲OP在尋找的東西,因爲它讓我超越了終點。

PS C:\brh> (ls .\deploy.ps1).LastWriteTime.DateTime 
Friday, December 12, 2014 2:33:09 PM 

PS C:\brh> 

請注意缺少額外的行,只有PowerShell用來分隔提示的行。現在可以將它分配給一個變量進行比較,或者像我一樣,保存在一個文件中供以後的會話讀取和比較。

1

稍微簡單一點 - 使用new-timespan cmdlet,它會從當前時間創建一個時間間隔。

ls | where-object {(new-timespan $_.LastWriteTime).days -ge 1} 

顯示所有未寫入今天的文件。