auto remove files

Home Forums Scripting PowerShell auto remove files

This topic contains 3 replies, has 2 voices, and was last updated by Avatar kathy 3 years ago.

Viewing 4 posts - 1 through 4 (of 4 total)
  • Author
    Posts
  • Avatar
    kathy
    Member
    #166399

    $location = Get-ChildItem \foo.barDrop_Zone
    $date = Get-Date
    foreach ($item in $location) {
    # Check to see if this is the readme folder
    if($item.PsIsContainer -and $item.Name -ne ‘_ReadMe’) {
    $itemAge = ((Get-Date) – $item.CreationTime).Days
    if($itemAge -gt 7) {
    Remove-Item $item.FullName -recurse -force
    }
    }
    else {
    # must be a file
    # you can check age and delete based on that or just delete regardless
    # because they didn’t follow the policy
    }
    }

    Avatar
    Ossian
    Moderator
    #191255

    And….?
    Are you
    a) posting this as information for others
    b) having a problem with the script?
    If (b), what is it?

    Moved to PowerShell forum anyway….

    Avatar
    kathy
    Member
    #305531

    Hi,

    Thanks for your reply…

    I have search and made this script as below but the problem with this script is its not checking the date stamp in the file and it remove all the files from the specific folder

    ==================================================================

    # Delete all Files in drive older than 3 day(s)
    $Path = “C:appadministratoradminabcpqr”
    $Daysback = “-2”

    $CurrentDate = Get-Date
    $DatetoDelete = $CurrentDate.AddDays($Daysback)
    Get-ChildItem $Path | Where-Object { $_.LastWriteTime -lt $DatetoDelete } | Remove-Item

    ==================================================================

    what could be issue, ..please help

    Avatar
    Ossian
    Moderator
    #191392

    Just tested the code (with a -WhatIf) on a directory containing a range of file dates and it seems to work perfectly OK – the correct set of files is identified and LastWriteTime is definitely used

    Suggest you replace the “Remove-Item” with “Format-Table” and check the list of files returned, also ensure there are some files which should not be deleted

    Note I also changed the path, but that should make no difference

Viewing 4 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic.