Home ยป How to Get the Last Modified File in Directory Using PowerShell

How to Get the Last Modified File in Directory Using PowerShell

To get the last modified file in the directory using PowerShell, you can use the Get-ChildItem cmdlet to retrieve all files from the specified directory and then sort them based on their last write time.

The following method shows how you can do it.

Method 1: Get the last modified file in the directory

# Specify the directory path
$directoryPath = "C:\temp\log\"

# Retrieve all files and sort them based on last write time
Get-ChildItem -Path $directoryPath -File | Sort-Object LastWriteTime -Descending | Select-Object -First 1

This example returns the most recently modified file in the directory based on their last write time.

The following example shows how you can use this method with syntax.

Get the Last Modified File in the Directory

You can use the Get-ChildItem cmdlet to retrieve the files from the directory with the Sort-Object cmdlet to sort files based on their LastWriteTime in descending order and select the first item to get last modified or newest file in the directory.

# Specify the directory path
$directoryPath = "C:\temp\log\"

# Retrieve all files and sort them based on last write time
Get-ChildItem -Path $directoryPath -File | Sort-Object LastWriteTime -Descending | Select-Object -First 1

Output:

Powershell get last modified file in directory
Powershell gets the last modified file in the directory

After running the script, the PowerShell will output the full path of the last modified file in the specified directory.

Conclusion

I hope the above article on getting the last modified file in the directory using PowerShell is helpful to you.

The Sort-Object cmdlet with the property LastWriteTime -Descending parameters sorts the file based on their LastWriteTime property in descending order, so the newest file appears first.

You can find more topics about Active Directory tools and PowerShell basics on the ActiveDirectoryTools home page.