0

I'm trying to write a script that will copy a file to a second location, when the file changes. For that I'm using an if statement like this:

if (
(Get-ChildItem C:\folder2\file).LastWriteTimeUtc -ge (Get-ChildItem C:\folder1\file).LastWriteTimeUtc
)
{exit}
else
{#execute}

Right now the files are exactly the same and if I run

(Get-ChildItem C:\folder2\file).LastWriteTimeUtc

the result for both is

Friday, 15. April 2022 23:32:09

My issue is that both LastWriteTimes appear to be the same and the script shouldn't do anything, but it does. And the reason for that is, that even though both values seem to be the same they are not and comparing them with "-eq" returns "False".

I'm using PowerShell 5.1

TWi
  • 1
  • 2
  • Do you see a difference when comparing `(Get-ChildItem ...).LastWriteTimeUtc.Ticks` of both files ? – Santiago Squarzon May 09 '22 at 22:48
  • There are 2 possible reasons for this that I can imagine. 1. Either the datetimes are not equal or the LHS is lower than the RHS (hence why check the files `Ticks` property) or 2. The files path have wildcard characters and `Get-ChildItem` may be returning more than one file, to fix thid you can use `-LiteralPath` – Santiago Squarzon May 09 '22 at 23:01
  • @SantiagoSquarzon That's it. There is a difference of about 300k ticks between the files. Is there a way to equalize the values so I can use them for the comparison? – TWi May 10 '22 at 09:30
  • Have a look at [How to truncate milliseconds off of a .NET DateTime](https://stackoverflow.com/q/1004698/9898643) – Theo May 10 '22 at 09:53

1 Answers1

0

Thanks for all the replies. I'm sorry if I wasn't as specific as I should have been. But because of them I found an answer that should work for me.

First I get both dates as ticks and convert them to strings

$datef2 = (Get-ChildItem C:\folder2\file).LastWriteTimeUtc.Ticks.ToString()
$datef1 = (Get-ChildItem C:\folder1\file).LastWriteTimeUtc.Ticks.ToString()

then I replace the last 7 digits with 0 (which is everything small than a second) and compare them

($datef2.Substring(0,$datecb.Length-7) + "0000000") -ge ($datef1.Substring(0,$datenx.Length-7) + "0000000")

Might not be the most elegant solution but it gives the if statement the correct values.

TWi
  • 1
  • 2