PS script to delete temp files skip the locked files

This topic contains 5 replies, has 2 voices, and was last updated by Profile photo of Mohit Sood Mohit Sood 4 months, 1 week ago.

  • Author
    Posts
  • #48280
    Profile photo of Mohit Sood
    Mohit Sood
    Participant

    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

  • #48282
    Profile photo of Don Jones
    Don Jones
    Keymaster

    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.

  • #48285
    Profile photo of Mohit Sood
    Mohit Sood
    Participant

    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

  • #48290
    Profile photo of Don Jones
    Don Jones
    Keymaster

    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!

  • #48300
    Profile photo of Mohit Sood
    Mohit Sood
    Participant

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

  • #48459
    Profile photo of Mohit Sood
    Mohit Sood
    Participant

    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?

You must be logged in to reply to this topic.