Reputation: 483
I want to run something like the below script every 10 minutes.
I have file A and file B. Every 10 minutes, I want to check if File A is newer than File B. If so, I want to set the LastWriteTime of file B to the current date. I believe my if
statement is wrong... How can I fix it?
$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)
}
I think in the above example, I'm only setting the variable $b to the current date...I want to set the LastWriteTime of the actual file to the current date.
Upvotes: 2
Views: 5398
Reputation: 198
Try this. It worked for me in PowerShell 5.
In order to change the date of LastWriteTime, you have to write to file again, for example,
$a = Get-Item fileA.txt
$b = Get-Item fileB.txt
if(($a.LastWriteTime) -lt ($b.LastWriteTime))
{
fileB.txt | add-content -Value ''
}
Upvotes: 1
Reputation: 624
You could do something similar to the following to change the last write time of a file:
$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."
}
More information on the Namespace, .NET class, and associated methods used in the above code can be found Here.
Hope this helps!
Upvotes: 2
Reputation: 2626
Try using the less than operator in the if statement and using the Get-ChildItem
to get the file instead of the LastWriteTime
property.
$a = Get-ChildItem tst1.txt
$b = Get-ChildItem tst2.txt
if(($a.LastWriteTime) -lt ($b.LastWriteTime))
{
$b.LastWriteTime = (Get-Date)
}
Learn more about operators here.
Upvotes: 4