Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell Get-ChildItem most recent file in directory

Tags:

powershell

We produce files with date in the name. (* below is the wildcard for the date) I want to grab the last file and the folder that contains the file also has a date(month only) in its title.

I am using PowerShell and I am scheduling it to run each day. Here is the script so far:

  $LastFile = *_DailyFile   $compareDate = (Get-Date).AddDays(-1)   $LastFileCaptured = Get-ChildItem -Recurse | Where-Object {$LastFile.LastWriteTime                  -ge $compareDate} 
like image 217
user977645 Avatar asked Mar 12 '12 22:03

user977645


People also ask

How do I get latest PowerShell file?

Getting a single latest from a given Directory using file extension filter. One can use a combination of properties like LastWriteTime and Select -First 1 to get the latest file in the given directory.

How do I get LastWriteTime in PowerShell?

Use the Get-ChildItem LastWriteTime attribute to find the list of files with lastwritetime. Get-ChildItem in the PowerShell gets one or more child items from the directory and subdirectories.

Which PowerShell cmdlet can be used to read the content of recently downloaded files?

Description. The Get-Content cmdlet gets the content of the item at the location specified by the path, such as the text in a file or the content of a function. For files, the content is read one line at a time and returns a collection of objects, each of which represents a line of content.

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.


1 Answers

If you want the latest file in the directory and you are using only the LastWriteTime to determine the latest file, you can do something like below:

gci path | sort LastWriteTime | select -last 1 

On the other hand, if you want to only rely on the names that have the dates in them, you should be able to something similar

gci path | select -last 1 

Also, if there are directories in the directory, you might want to add a ?{-not $_.PsIsContainer}

like image 80
manojlds Avatar answered Sep 21 '22 22:09

manojlds