Author Posts

July 26, 2016 at 2:57 pm

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.


July 26, 2016 at 3:00 pm

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.

July 26, 2016 at 3:13 pm

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

July 26, 2016 at 3:25 pm

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!

July 26, 2016 at 4:12 pm

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

July 27, 2016 at 2:28 pm

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?