none
Help with powershell script to delete *.bak files older N number of days RRS feed

  • Question

  • I have below powershell script to delete 21 days older files into D:\Backup\Full

    Script runs and display the files older than 21 days but they are not deleting

    the user runs script has full rights on folder

    extension of files into folder are *.bak

    forfiles-p"D:\Backup\Full"-s-m*.*/D-21/C"cmd /c echo @files"


    Muhammad Mehdi

    Wednesday, September 30, 2015 8:49 PM

Answers

  • forfiles.exe is a command-line tool that has nothing whatsoever to do with PowerShell. (In fact, is is not needed at all if you use PowerShell.)

    In PowerShell, we would write something like this:


    PS C:\> Get-ChildItem D:\Backup\Full\* -Include *.bak | Where-Object {
      $_.LastWriteTime -le (Get-Date).AddDays(-21) } | ForEach-Object {
      Remove-Item $_ -WhatIf
    }
    

    (not tested) Of course, you would remove the -WhatIf parameter to actually remove the files.


    -- Bill Stewart [Bill_Stewart]

    Wednesday, September 30, 2015 10:01 PM
    Moderator

All replies

  • Why would you expect that line to delete files?

    Try reading the help for the command to see how it works.


    \_(ツ)_/

    Wednesday, September 30, 2015 8:56 PM
  • thanks found the right one

    forfiles /p "D:\Backup\Full" /s /m *.* /c "cmd /c Del @path" /d -21


    Muhammad Mehdi

    Wednesday, September 30, 2015 9:57 PM
  • forfiles.exe is a command-line tool that has nothing whatsoever to do with PowerShell. (In fact, is is not needed at all if you use PowerShell.)

    In PowerShell, we would write something like this:


    PS C:\> Get-ChildItem D:\Backup\Full\* -Include *.bak | Where-Object {
      $_.LastWriteTime -le (Get-Date).AddDays(-21) } | ForEach-Object {
      Remove-Item $_ -WhatIf
    }
    

    (not tested) Of course, you would remove the -WhatIf parameter to actually remove the files.


    -- Bill Stewart [Bill_Stewart]

    Wednesday, September 30, 2015 10:01 PM
    Moderator