PS script to delete temp files skip the locked files

Hello All,

I am new to PS and was trying to build an automated OS script to delete temp files from one our servers on specific location, skips the locked files and delete the rest.

Thanks for help in advance.

Mohit

Welcome! So, did you have a specific question, then? Have you already tried something and run into troubles? We’re all volunteers, here, so we can’t write a script for you, but if you have a question about something we’re happy to try and point you to an answer.

yes i wrote a script below i just want to display results once its done and skip the locked files:-

$limit = (Get-Date).AddDays(-5)
$path = “\ServerName\C$\Program Files\temp”

Get-ChildItem -Path $path -Recurse -Force | Where-Object { !$.PSIsContainer -and $.CreationTime -lt $limit } | Remove-Item -Force

So, unfortunately there’s no way for PowerShell to know that a file is locked until it tries to access it. In terms of displaying what gets removed:

Get-ChildItem -Path $path -Recurse -Force | 
Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } | 
ForEach-Object {
 Write-Output $_
 $_ | Remove-Item -Force
}

That will display the files that Remove-Item is attempting to remove. If you want to “catch” the error caused by trying to remove a locked file, that’s more complex.

Get-ChildItem -Path $path -Recurse -Force | 
Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } | 
ForEach-Object {
 Write-Output $_
 try {
   $_ | Remove-Item -Force -ErrorAction Stop
 } catch {
   Write-Warning "Could not remove $($_.FullName)"
 }
}

I’d suggest reading “The Big Book of PowerShell Error Handling” (free, on our ebooks menu) so you understand more about error handling. What I’m doing in that example might not be what you want, but reading the book will help you understand what to change to get what you want.

Good luck!

Thanks Alot. This helps alot and i will read more about error handling.

I had one question:-

Is it possible to add multiple paths in the code for it to delete files from?

Other then writing new script for every path?