比较PowerShell中'if'语句中的LastWriteTime

时间:2016-07-04 14:31:36

标签: powershell

我想每10分钟运行一次类似下面的脚本。

我有文件A和文件B.每隔10分钟,我想检查文件A是否比文件B更新。如果是这样,我想将文件B的LastWriteTime设置为当前日期。我相信我的if陈述错了......我该如何解决?

$a = Get-Item c:\users\testuser\desktop\test.xml | select LastWriteTime

$b = Get-Item C:\users\testuser\Desktop\test.swf | select LastWriteTime

if($a < $b)
{
    $b.LastWriteTime = (Get-Date)
}

我认为在上面的例子中,我只是将变量$ b设置为当前日期...我想将实际文件的LastWriteTime设置为当前日期。

3 个答案:

答案 0 :(得分:2)

您可以执行与以下内容类似的操作来更改文件的上次写入时间:

$File1 = Get-ChildItem -Path "C:\Temp\test1.txt"
$File2 = Get-ChildItem -Path "C:\Temp\test2.txt"

#System.IO is a namespace of the file class in .NET and GetLastWriteTime/SetLastWriteTime are methods of this class.
if ([System.IO.File]::GetLastWriteTime($File1) -lt [System.IO.File]::GetLastWriteTime($File2))
    {
        Write-Output  "File1 LastWriteTime is less than File2, Setting LastWriteTime on File2."
            ([System.IO.File]::SetLastWriteTime($File2,(Get-Date)))
    }
ELSE
    {
        Write-Output "File1 LastWriteTime is not less than File2 LastWriteTime."
    }

可以找到有关上述代码中使用的命名空间,.NET类和相关方法的更多信息Here

希望这有帮助!

答案 1 :(得分:1)

尝试在if语句中使用less than运算符,并使用Get-ChildItem获取文件而不是LastWriteTime属性。

$a = Get-ChildItem tst1.txt  
$b = Get-ChildItem tst2.txt 

if(($a.LastWriteTime) -lt ($b.LastWriteTime))
{ 
    $b.LastWriteTime = (Get-Date) 
}

详细了解运营商here

答案 2 :(得分:1)

试试这个。它在PowerShell 5中对我有用。

要更改LastWriteTime的日期,您必须再次写入文件,例如

$a = Get-Item fileA.txt
$b = Get-Item fileB.txt

if(($a.LastWriteTime) -lt ($b.LastWriteTime))
{
    fileB.txt | add-content -Value ''
}