SimonS
SimonS

Reputation: 1973

gci with LastWriteTime doesn't return the correct file-object

I have a File in a Folder with the following LastWriteTime Property:

LastWriteTime
-------------
08.09.2016 07:46:18

Why doesn't any of these command return the File object?

gci . | ? {$_.LastWriteTime -like '*08.09.2016*'}

gci . | ? {$_.LastWriteTime -eq '08.09.2016'}

gci . | ? {$_.LastWriteTime -eq '08.09.2016 07:46:18'}

My task is to get all Files which were created on 08.09.2016 in a folder recursively and I know how to do that, but my LastWriteTime compare doesn't want to work. why?

Upvotes: 0

Views: 329

Answers (1)

Andrey Marchuk
Andrey Marchuk

Reputation: 13483

Your problem is that $_.LastWriteTime is of Type DateTime and you are comparing it with string. You need to create the DateTime object yourself, like:

[datetime]::ParseExact("31/12/1900", "dd/MM/yyyy", $null)

You may also convert the $_.LastWriteTime to string, like:

$_.LastWriteTime.ToShortTimeString()

but keep in mind that the results will be different on computers with different culture settings. Option 1 is the way to go. Complete example looks like this:

gci . | ? {$_.LastWriteTime.Date -eq [datetime]::ParseExact("08/09/2016", "dd/MM/yyyy", $null)}

Upvotes: 2

Related Questions