Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit the number of Get-ChildItem results

Tags:

powershell

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?

like image 300
TheSavo Avatar asked Mar 14 '12 16:03

TheSavo


People also ask

How do I Get-ChildItem to exclude folders?

To exclude directories, use the File parameter and omit the Directory parameter, or use the Attributes parameter. To get directories, use the Directory parameter, its "ad" alias, or the Directory attribute of the Attributes parameter.

What does Get-ChildItem do in PowerShell?

The Get-ChildItem cmdlet gets the items in one or more specified locations. If the item is a container, it gets the items inside the container, known as child items. You can use the Recurse parameter to get items in all child containers and use the Depth parameter to limit the number of levels to recurse.

How do I filter data in PowerShell?

Using the Where-Object and Select-Object commands allows you to easily control which items you are working on in PowerShell. You can use these commands to either filter the data you are viewing or to limit actions (such as stopping services or removing files) to those that match the filters you define.

How do you get the full path of ChildItem?

Use the Get-ChildItem cmdlet in PowerShell to get the files in the folder using the file filter and using the Select-Object cmdlet to get the full path of the file using ExpandProperty FullName.


1 Answers

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.

like image 140
manojlds Avatar answered Sep 24 '22 16:09

manojlds