Script to delete old files from server

Welcome Forums General PowerShell Q&A Script to delete old files from server

This topic contains 14 replies, has 5 voices, and was last updated by

 
Inactive
6 months, 2 weeks ago.

  • Author
    Posts
  • #101511

    Inactive
    Points: 0
    Rank: Member

    A folder contain 'n' number of files. In that, I want to delete only file names which starts with 'Tcp', that too which are older than 30 days and latest files should remain as it is. I have a script but its deleting all the tcp files inside the folder.
    But need to delete only files, whose name starts with TCP, which are created 30 days back.

    Can someone please help me on this?

  • #101515

    Participant
    Points: 342
    Helping Hand
    Rank: Contributor

    There are a couple million examples of this. Have you tried anything? Have you tried to search?

    • #101526

      Inactive
      Points: 0
      Rank: Member

      Yes Rob.

      I got couple of scripts, but it's deleting all the files inside the folder.

      script 1)

      $limit = (Get-Date).AddMinutes(-1)
      $path = "C:\Users\mpradeep\Downloads\sample nuget apps\"
      $include = "Tcp.*"

      Get-ChildItem -Path $path -include $include | Where-Object {$_.CreationTime -lt $limit} | Remove-Item
      —————————————————————
      script 2)

      $Now = Get-Date
      $Minutes = "-1"
      $TargetFolder = "C:\Users\mpradeep\Downloads\sample nuget apps\"
      $Extension = "Tcp.*"
      $LastWrite = $Now.AddDays(-$Minutes)
      $Files = Get-Childitem $TargetFolder -Include $Extension -Recurse | Where {$_.LastWriteTime -le "$LastWrite"}

      foreach ($File in $Files)
      {
      if ($File -ne $NULL)
      {
      write-host "Deleting File $File" -ForegroundColor "DarkRed"
      Remove-Item $File.FullName | out-null
      }
      else
      {
      Write-Host "No more files to delete!" -foregroundcolor "Green"
      }
      }

  • #101518

    Keymaster
    Points: 1,704
    Helping HandTeam Member
    Rank: Community Hero

    It'd be better for you to bring some code that you've written and ask a specific question about it. We're not set up to write complete solutions for you. If you're having trouble just understanding the logic you'd use, it's fine to ask that, too – folks can outline the logical steps they'd use. But, to echo the previous comment, this is something that's been asked here hundreds of times – it might be worth a search of the forums to see what's already been asked and answered.

  • #101521

    Inactive
    Points: 0
    Rank: Member

    Yes Rob.

    I got couple of scripts, but it's deleting all the files inside the folder.

    script 1)

    $limit = (Get-Date).AddMinutes(-1)
    $path = "C:\Users\mpradeep\Downloads\sample nuget apps\"
    $include = "Tcp.*"

    Get-ChildItem -Path $path -include $include | Where-Object {$_.CreationTime -lt $limit} | Remove-Item
    —————————————————————
    script 2)

    $Now = Get-Date
    $Minutes = "-1"
    $TargetFolder = "C:\Users\mpradeep\Downloads\sample nuget apps\"
    $Extension = "Tcp.*"
    $LastWrite = $Now.AddDays(-$Minutes)
    $Files = Get-Childitem $TargetFolder -Include $Extension -Recurse | Where {$_.LastWriteTime -le "$LastWrite"}

    foreach ($File in $Files)
    {
    if ($File -ne $NULL)
    {
    write-host "Deleting File $File" -ForegroundColor "DarkRed"
    Remove-Item $File.FullName | out-null
    }
    else
    {
    Write-Host "No more files to delete!" -foregroundcolor "Green"
    }
    }

  • #101524

    Inactive
    Points: 0
    Rank: Member

    yeah don.

    I searched and got couple of answer for above query, even i altered the script too but script didn't worked as expected, its deleting all the files inside the folder.
    Some minor changes and condition to be included on the script, am not getting that.
    So thought to post it here.
    As i am very new to PS, i am trying to learn the things.

  • #101532

    Participant
    Points: 297
    Helping Hand
    Rank: Contributor
    $limit = (Get-Date).AddMinutes(-1)

    and

    Where-Object {$_.CreationTime -lt $limit}

    Means "everything more than a minute old". Sure the comparison is 'lt' (less than) but in a date value comparison [less than one minute ago] means everything earlier than whatever one minute ago was.

    That's what you're targeting and deleting here.

    So you need to change your condition to match your requirements:

    $limit = (Get-Date).AddDays(-30)
    $Name = "Tcp*"
    $Files = Get-Childitem $TargetFolder -Include $Name #... rest of the script
    • #101535

      Inactive
      Points: 0
      Rank: Member

      hey joel,
      Thanks.

      But i was trying in my local server instead of production, instead of testing for 30 days i was trying for minutes.
      I was testing, which ever the files are created less than 1 minutes, it should not get deleted and older files should get deleted.
      especially the file name starts from "tcp.*". but here all the files are getting deleted.

      I have tried, even though it didn't worked.
      Please help me out.

  • #101551

    Participant
    Points: 342
    Helping Hand
    Rank: Contributor
    • Include and Exclude for Get-ChildItem don't always work as expected and are typically extensions. It's better to do the filter in the path or in a Where filter after you get all files. We always try to filter left, so we'll use the path
    • The Where filter in this case is looking for files less than a date that we subtracted 30 days from
    • We can then pipe this to Remove-Item. Use the WhatIf switch to see what will be deleted rather than delete the files.
    Get-ChildItem 'C:\Scripts\Test\tcp*' | 
    Where{$_.LastWriteTime -lt (Get-Date).AddDays(-30)} |
    Remove-Item -Force -WhatIf
    

    Results:

    PS C:\Users\Rob> Get-ChildItem 'C:\Scripts\Test'
    
    
        Directory: C:\Scripts\Test
    
    
    Mode                LastWriteTime         Length Name                                                                                                                                             
    ----                -------------         ------ ----                                                                                                                                             
    -a----        5/31/2018  12:02 PM              0 blue.txt                                                                                                                                         
    -a----        5/31/2018  12:02 PM              0 green.txt                                                                                                                                        
    -a----        4/16/2018  12:12 PM              0 tcp123.txt                                                                                                                                       
    -a----        4/16/2018  12:12 PM              0 tcp321.txt                                                                                                                                       
    
    
    
    PS C:\Users\Rob> Get-ChildItem 'C:\Scripts\Test\tcp*' | 
    Where{$_.LastWriteTime -lt (Get-Date).AddDays(-30)} |
    Remove-Item -Force -WhatIf
    
    What if: Performing the operation "Remove File" on target "C:\Scripts\Test\tcp123.txt".
    What if: Performing the operation "Remove File" on target "C:\Scripts\Test\tcp321.txt".
    
  • #101562

    Inactive
    Points: 0
    Rank: Member
    PS C:\Users\Pra> Get-ChildItem 'C:\Scripts\Tcp'
    
    
        Directory: C:\Scripts\Tcp
    
    
    Mode                LastWriteTime         Length Name                                                                                                                                             
    ----                -------------         ------ ----                                                                                                                                             
    -a----        5/31/2018  08:00 PM              0 pradeep.txt                                                                                                                                         
    -a----        5/31/2018  10:00 PM              0 ashwin.txt                                                                                                                                        
    -a----        5/31/2018  00:54 AM              0 tcp.1.2a.3.txt                                                                                                                                       
    -a----        5/30/2018  10:12 PM              0 tcp.3ndc.21.txt 
    -a----        5/30/2018  10:11 PM              0 tcp.txt 
    -a----        5/30/2018  01:10 PM              0 tcp.23.c21.txt                                                                                                                                      
    
    
    
    PS C:\Users\Pra> Get-ChildItem 'C:\Scripts\tcp.*' | 
    Where{$_.LastWriteTime -lt (Get-Date).AddDays(-1)} |
    Remove-Item -Force 

    In the above sample files, only tcp.3ndc.21.txt and tcp.23.c21.txt should be deleted. But in my case, even tcp.txt is being deleted. Can you please guide me on this?

  • #101566

    Participant
    Points: 342
    Helping Hand
    Rank: Contributor

    Try changing your filter:

    Get-ChildItem 'C:\Scripts\Test\tcp.*.txt' | 
    Where{$_.LastWriteTime -lt (Get-Date).AddDays(-30)} |
    Remove-Item -Force -WhatIf
    
    • #101572

      Inactive
      Points: 0
      Rank: Member

      Thanks Rob.

      It Worked for me.
      if i need any help, i get back to you.

    • #101918

      Inactive
      Points: 0
      Rank: Member

      hi rob,

      How to run/execute a PS script on remote servers ??
      i just used like UCN path of the script,
      \\server-name\d$\Program-Files\script.ps1

      But it didn't worked !

      please help me,
      1) If i wanted to include remote server path on the script, what changes to be done?
      2) if i want to execute it directly using the path, what changes do be done ?

      Thanks in advance.

  • #101593
    js

    Participant
    Points: 326
    Helping Hand
    Rank: Contributor

    Yes, there's a powershell bug where "get-childitem -include" only works with -recurse or a wildcard in the path. It's fixed in PS6.

    I like doing date comparisons this way, with an implied casting of '30' to [timespan]:

    ls | where { (get-date) - $_.lastwritetime -gt '30' }           
    

    Maybe this is better.

    $30days = New-TimeSpan -Days 30
    ls | where { (get-date) - $_.lastwritetime -gt $30days }
    • #101957

      Inactive
      Points: 0
      Rank: Member

      Thanks JS

The topic ‘Script to delete old files from server’ is closed to new replies.