2009-06-19 237 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} 

显示所有未写入今天的文件。