PowerShell Get Last Modified File in Directory

PowerShell get last modified file in directory

For this article, our working directory will be C:\Test1 containing two files named File1.txt and File2.txt.

Using Get-ChildItem along with Sort-Object Cmdlet

Use the Get-ChildItem cmdlet with Sort-Object` cmdlet to get last modified file in directory in PowerShell. Sort-Object cmdlet will sort the File object by LastWriteTime property.

The code uses the Get-ChildItem cmdlet to retrieve a list of files and directories within a specified directory, which is C:\Test. Next, the result of the Get-ChildItem cmdlet is passed to the Sort-Object cmdlet via the pipe symbol (|). Finally, the LastWriteTime property, which indicates when the file or directory was last updated, is used to sort the list of files and directories using the Sort-Object cmdlet.

The most recently updated file or directory is at the top of the list when the parameter -Descending is used to sort the list in descending order. Next, the pipe symbol is used again to pass the sorted list to the Select-Object cmdlet. Finally, the Select-Object cmdlet retrieves the first item in the sorted list, the most recently modified file or directory. The parameter -First 1 is used to specify that only the first item should be retrieved.

In case, you want to find out last modified file in directory and sub-directories, you can -Recurse option.

Using Get-Item Cmdlet with Sort-Object

Use the Get-ChildItem cmdlet with Sort-Object to get last modified file in directory in PowerShell.

Like the preceding code block, the above snippet uses the Get-Item cmdlet. The output of Get-ChildItem is sorted by the LastWriteTime attribute in descending order, placing the most recently updated file at the top of the list. Like the last code, the Select-Object cmdlet retrieves the most recently updated file. The.FullName is a property of the selected item that retrieves the item’s Name. Finally, the Get-Item command retrieves the item with the full path returned by the previous pipeline and returns information about the item, such as the Name, Length, Mode, LastWriteTime, etc.

Using .Net Framework

Use the .Net framework class to get last modified file in directory in PowerShell.

First, we use the New-Object cmdlet to create a new DirectoryInfo object and assign it to the $directory variable. Then, we use the GetFiles() method to get all files in the directory. Finally, the GetFiles() output is piped to the Sort-Object cmdlet, where we used the -Descending parameter to sort the files in descending order by the LastWriteTime property.

Now, the Sort-Object cmdlet output is piped to the Select-Object cmdlet, which selects the first file from the sorted list using the -First parameter is set to 1. The final result is stored in the $file variable. And finally, output the full name (i.e., path and filename) of the selected file using the FullName property of $file.

Using the FileSystemWatcher Class

To get last modified file in directory in PowerShell, use the FileSystemWatcher Class:

  • Use New-Object to create a System.IO.FileSystemWatcher object to monitor a directory for file changes.
  • Set the Path property of the watcher to the directory(C:\Test1) to be monitored.
  • Set the Filter property of the watcher to monitor changes to all files in the directory.
  • Set the IncludeSubdirectories property of the watcher to monitor only the specified directory, not the subdirectories.
  • Enable the watcher to raise events when changes occur in the specified directory.
  • Register the watcher object to listen for the Changed event and run the script block when the event occurs.
  • Enter an infinite loop to keep the script running and waiting for events.
  • Use the Get-ChildItem cmdlet to retrieve the most recently modified file in the specified directory.
  • Sort the list of files by their LastWriteTime property in descending order.
  • Check if the selected file is not null and if its full name is different from the last modified file.
  • If the file meets the conditions in step 12, update the last modified file variable and write the file’s full name to the console.
  • Pause the script using Start-Sleep for a specified time (5 seconds) and continue monitoring the directory for changes.

The code creates a new instance of the System.IO.FileSystemWatcher class and sets its properties to monitor the C:\Test1 directory for any changes to any file using the *.* filter. In addition, the $watcher.IncludeSubdirectories property is set to $false, which means that the watcher will only monitor the specified directory and not its subdirectories.

The EnableRaisingEvents property is set to $true to enable the watcher to raise events when a change is detected. The code then initializes a $lastModifiedFile variable to $null and defines a $changedAction script block that will be executed when a file change event is detected.

The $changedAction script block retrieves the most recently modified file in the directory using the Get-ChildItem cmdlet and sorting by the LastWriteTime property in descending order. The Select-Object cmdlet selects the first item in the sorted list. If a file is found and its FullName is not equal to the value of $lastModifiedFile, the script block sets the $lastModifiedFile variable to the FullName of the found file and writes a message to the console indicating the name of the last modified file.

Finally, the Register-ObjectEvent cmdlet is used to register the $changedAction script block as the action to be executed when the FileSystemWatcher detects a change in the monitored directory. The script enters an infinite loop and periodically sleeps for 5 seconds, allowing the FileSystemWatcher to continue monitoring for file changes.

The script will run indefinitely until it is manually stopped by pressing Ctrl+C.

Considering the above solutions, multiple methods exist for getting the last modified file in a directory using PowerShell. The method you choose depends on your personal preferences.

That’s all about PowerShell get last modified file in directory.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *