TheSavo
TheSavo

Reputation: 583

Limit the number of Get-ChildItem results

I am writing a script that will log the changes to the modification date of a specific file. I only care about the single newest file. I want to capture that and save its name and Lastwritetime to a text file.

I am only finding results limiting recursion.

Is there a way to limit the number of results?

Upvotes: 44

Views: 65399

Answers (1)

manojlds
manojlds

Reputation: 301347

You can use the Select-Object:

Get-ChildItem . | Select-Object -last 1

If you want the latest file, something like:

Get-ChildItem . | Sort-Object LastWriteTime | select -last 1

And of course you can get only the properties that you are interested in with Select-Object as well:

Get-ChildItem .  | Sort-Object LastWriteTime | Select-Object -last 1 Name,LastWriteTime

And you can pipe that to Export-Csv.

Aliases can also be used, Get-ChildItemgci, Select-Objectselect, and Sort-Objectsort.

Upvotes: 60

Related Questions