I was given a task to find the oldest log file and the newest log file in the log folder.
To check if our logger is correctly working or not.
If you are just looking for the commands. Then here they are.
Oldest File -> Get-ChildItem -Path .\ -Filter *.txt | Sort-Object -Property CreationTime | Select-Object -First 1
Newest File -> Get-ChildItem -Path .\ -Filter *.txt | Sort-Object -Property CreationTime -Descending | Select-Object -First 1
For watch this article in action here.
[embed]https://youtu.be/a7rvmjO4zxc[/embed]
You just need to change -Path to your target folder in Get-ChildItem command.
Let us start, with writing commands.
First create a folder, where we will create our test files.
New-Item -ItemType Directory -Path TestFiles
Then move the the TestFiles folder.
Set-Location -Path .\TestFiles\
Now, we are inside our Test folder.
Next we write code to create 10 files. After each new file is created, the task will start sleeping for given number of seconds, which will be equal to the Sequence of the file.
for($FileSeq = 1; $FileSeq -le 10; ++$FileSeq) {
$FileName = "File_$FileSeq.txt";
New-Item -Type File -Name $FileName -Value "I am file number $FileSeq";
Write-Progress -Activity 'File Creation' -Status "File Created - $FileSeq/10" -PercentComplete ($FileSeq * 10);
if($FileSeq -lt 10) { Start-Sleep -Seconds $FileSeq; }
}
This is the screenshot, while the file creation task was in progress.
This is the screenshot after the task was complete.
To find the latest file, we will have to start writing the command to find the files. This will give all the .txt files in the current folder.
Get-ChildItem -Path .\ -Filter *.txt;
Next, we need to sort the files on CreationTime , which will give us files ordered from oldest to newest.
Get-ChildItem -Path .\ -Filter *.txt | Sort-Object -Property CreationTime ;
The above code will give us all the files, but to get the oldest, we need to select only one file.
Get-ChildItem -Path .\ -Filter *.txt | Sort-Object -Property CreationTime | Select-Object -First 1
This gives us the oldest file, File_1.txt. As, File_1.txt was created first, so, it is the oldest.
To get the latest/newest file we will do reverse sort on Creation Time. To do the reverse sorting, we have to pass the -Descending parameter in Sort-Object.
Get-ChildItem -Path .\ -Filter *.txt | Sort-Object -Property CreationTime -Descending | Select-Object -First 1
We get File_10.txt as the newest/latest file, because it was the last file which was created.