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.
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.
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.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With