PowerShell script to delete files older than a week

This is a simple PowerShell script to recursively delete all files that are older than 7 days in a specific directory:

$TargetFolder = “D:\Company\DropBox”
foreach ($i in Get-ChildItem $TargetFolder -recurse)
{
    if ($i.CreationTime -lt ($(Get-Date).AddDays(-7)))
    {
        Remove-Item $File.FullName -force
    }
}

And if you only want to include specific extensions, let’s say for example .html and .txt, a little addition to the script is required:

$TargetFolder = “D:\Company\DropBox”
foreach ($i in Get-ChildItem $TargetFolder -recurse -include *.txt, *.html)
{
    if ($i.CreationTime -lt ($(Get-Date).AddDays(-7)))
    {
        Remove-Item $File.FullName -force
    }
}

8 comments

  1. Hi Jeff,
     
    Just a word of caution. You are deleting files created more than a week ago, not files modified more than a week ago. It may be worth expanding your post to include last accessed and / or last written to.

    Love the blog and keep up the good work,

    Andrew

  2. Vijay Kumar says:

    Guys,

    This will not work for remote computers. Admins need to manage multiple computers. Below is the script that can be used to delete folders in multiple remote computers without having tio login to them.

    Below script will delete folders older than 15 days. you can change the $days parameter though

    D$Program Files (x86)Research In MotionBlackBerry Enterprise ServerLogs is the UNC path for Blackberry Log folder. You can change the directory where your logs/folders are located.

    list all your servername is servers.txt file and it should located in the same directory as this script. 

    #============Begin of the Script=======================

    cd C:ScriptsPowershellscriptsdeletefiles —-> change it to the directory you wanna out this script to

    $Days = “15” 
    $Now = Get-Date
    $LastWrite = $Now.AddDays(-$days)
    $server = get-content servers.txt
    foreach ($node in $server)
    {
    get-childitem -recurse “\$nodeD$Program Files (x86)Research In MotionBlackBerry Enterprise ServerLogs” | Where-Object {$_.LastWriteTime -le $LastWrite} | remove-item -recurse -force
    }

    #========End of the Script=================

    save the script as .ps1 and run it… You can schedule it via batch file… That why you need to add Change Directory command at the beginning of the script.. 

    Have fun..

  3. Jeff Wouters says:

    Hi Vijay,You’ve converted what I did in a couple of lines in just one, very nice, one liner (which I’m a great fan of btw!).
    I totally agree that admins mostly manage multiple devices.However, using a batch file to schedule a job sound illogical to me.How I would run a powershell command on multiple targets (using your one liner instead of my multiple lines):
    $sessions = new-PSSession -computername (import-csv D:Tempservers.csv)invoke-command -session $sessions -ScriptBlock {get-childitem -recurse “D:Program Files (x86)Research In MotionBlackBerry Enterprise ServerLogs” | Where-Object {$_.LastWriteTime -le $LastWrite} | remove-item -recurse -force} -AsJob
    This way you run the commands locally on each target and not through connecting to the admin share of a drive and now you won’t need to add the Change Directory at the beginning of the script.
    But this is just my way of doing this… you could schedule a job by using the Windows Task Scheduler on the remote systems, on a management system where you run the above command or whatever other approach you prefer.Jeff.

  4. Vijay Kumar says:

    Hi Jeff,

    In my environment, My account doesn’t have access to all servers. That’s why i use batch file, scheduled it and run as different account. I prefer to run all my scripts from my test machine without having login to or create scheduled task in remote servers.

    in that way, Batch file will come in handy 🙂

    It’s my preferred way Jeff 🙂

  5. Jeff Wouters says:

    If those are the only reasons to use a batch script, than you could use the -Credential parameter with the New-PSSession cmdlet:
    $sessions = new-PSSession -computername (import-csv D:Tempservers.csv) -Credential domainnameadminuser
    invoke-command -session $sessions -ScriptBlock {get-childitem -recurse “D:Program Files (x86)Research In MotionBlackBerry Enterprise ServerLogs” | Where-Object {$_.LastWriteTime -le $LastWrite} | remove-item -recurse -force} -AsJob
    But when you’re on a non-domain laptop at a customers site with  multiple domains, I would definitely see a use case to use batch scripts.

  6. Vijay Kumar says:

    Well, i tried that before but didn’t work as expected. Thanks the command Jeff. will give it a try again…

  7. Deepali Gupta says:

    hello

    I am on the verge of creating a Powershell script.
    I have 10 windows servers. On these servers i want to delete files older than 7 days from C:\Temp location.

    Can you pls help me?

Leave a Reply

Your email address will not be published. Required fields are marked *