Thursday, November 10, 2022

Why and How to get last modified file in Windows PowerShell?

Why ?

If you have a man logs file in same folder and it is rotated many times that may lead you have more than 10 files in the same day, you may have a case to check file each minute to ensure for example if any error or for any other reason, it will be a good optimizing in your code to test last file instead of checking all generated file.

How ?

Below is sample script to get the last modified file from wildcard list:

1- using the below PowerShell code, the last output will the last modified file, I am assuming you have a list of file with date/time in same folder:

$log_path = "{path_to_files}"

$log_files =  "{file_name_txt}"+(Get-Date).ToString('yyyyMMdd')+"*.log";

$logfile_name =  Get-ChildItem -Path $log_path -Recurse -Filter $log_files  | sort LastWriteTime |select -last 1  | select-object -expandproperty name;

$logfile_path = $log_path+$logfile_name;

 

print $logfile_path

No comments:

Post a Comment

Why and How to install Grid 19c on RHEL 8?

  Why ? Simply we will be requested to install Oracle Grid RAC DB on Redhat RHEL 8, below is my note for this installation . How ? 1-  OS in...