Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find the newest file in a directory using a PowerShell script?

Tags:

powershell

If, for example, I have a directory which contains the following files:

Test-20120626-1023.txt Test-20120626-0710.txt Test-20120626-2202.txt Test-20120626-1915.txt Test-20120626-1142.txt 

As you can see, each file name contains the time of creation which is in a sortable format.

How do I find the name of the latest file name (in this case Test-20120626-2202.txt) and store it in variable?

Note: The directory path is also stored in a variable if it makes any difference.

like image 574
Dusan Avatar asked Jun 26 '12 15:06

Dusan


People also ask

What is new item in PowerShell?

The New-Item cmdlet creates a new item and sets its value. The types of items that can be created depend on the location of the item. For example, in the file system, New-Item creates files and folders. In the registry, New-Item creates registry keys and entries.

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.

How do I get a list of files in a directory in PowerShell?

If you want to list files and directories of a specific directory, utilize the “-Path” parameter in the “Get-ChildItem” command. This option will help PowerShell list all the child items of the specified directory. The “-Path” parameter is also utilized to set the paths of one or more locations of files.


2 Answers

You could try something like this:

$dir = "C:\test_code" $latest = Get-ChildItem -Path $dir | Sort-Object LastAccessTime -Descending | Select-Object -First 1 $latest.name 
like image 106
James Berkenbile Avatar answered Oct 02 '22 01:10

James Berkenbile


If the name is the equivalent creation time of the file property CreationTime, you can easily use:

$a = Dir | Sort CreationTime -Descending | Select Name -First 1 

then

$a.name 

contains the name file.

I think it also works like this if name always have the same format (date and time with padding 0, for example, 20120102-0001):

$a = Dir | Sort Name -Descending | Select Name -First 1 
like image 42
CB. Avatar answered Oct 02 '22 02:10

CB.