user3088768
user3088768

Reputation: 21

To get last modified time in PowerShell

I got the code here to search a file and its content, but how do I get the last modified time?

Get-ChildItem d:\* -filter $fname* | Select-String -Pattern "exit" | Write-Host - $_.Lastwritetime

Upvotes: 2

Views: 15823

Answers (2)

vonPryz
vonPryz

Reputation: 24071

You can easily find out the properties by using the Get-Member cmdlet. For example,

gci test.txt | gm
# Output
   TypeName: System.IO.FileInfo

Name                      MemberType     Definition
----                      ----------     ----------
Mode                      CodeProperty   System.String Mode{get=Mode;}
AppendText                Method         System.IO.StreamWriter AppendText()
CopyTo                    Method         System.IO.FileInfo CopyTo(string destFileName)
...

Another way is to use GetType() to get, well, just the object's type.

(gci test.txt).GetType()

IsPublic IsSerial Name                  BaseType
-------- -------- ----                  --------
True     True     FileInfo              System.IO.FileSystemInfo

Note the TypeName. It's a .NET class, for which David already linked the relevant MSDN documentation page.

It's worth noting that Get-Childitem has multiple result types. That is, you'll get just a System.IO.FileSystemInfo when gci targets a file. When it targets a directory, you'll get an array of System.IO.DirectoryInfo objects.

Upvotes: 2

David Martin
David Martin

Reputation: 12248

You already have the last modified time:

CreationTime   = Created
LastWriteTime  = Modified
LastAccessTime = Accessed

See here for more details.

I think your problem is you are using Select-String which returns a MatchInfo object and you are expecting a FileInfo.

Get-ChildItem d:* -filter $fname* | Select-String -Pattern "exit" | group path | %{ (get-item $_.Name).LastWriteTime }

Grouping the results of select-string by path and then enumerating the names should give you what you want.

Upvotes: 6

Related Questions