PowerShell: Script to delete files older than X days

Hi All,
I am testing a script to delete files and I have it written down in my notepad as below:
$foldername = $args[0]
$maxage =      $args[1]
gci $foldername | Where-object {($_-is [io.fileinfo]) -and ($_.lastwritetime -lt (get-date).AddDays(-$maxage) ) } |
remove-item -whatif
Question: When i try to run the script and  pass the parameters $foldername and 30 it doesn't return anything. I am expecting it to return with -Whatif
To execute the script I wrote:
.\myscipts\del.ps1  cmd2 30
cmd2 is the name of the folder in my drive and 30 is ($maxage)  number of days old.
Thank-you
SQL 75

Thansks jrv, looks good! One more thing I wanted to ask do you know what it means by the error:
"An Empty Pipe Element is not Allowed" I altered my script a bit but it gives me this error. and I am passing no parameters when i call the script. My Script I created is below:
$name = $args[0]
$chew = $args[1]
IF ( $args.count -lt 2)  { Write-host "Please provide 2 parameters for this to work"
                exit 1 }
GCI $name | Where-object { $_-is [io.fileinfo]  -and ($_.lastwritetime -lt (get-date).AddDays(-$chew))}
 | remove-item -whatif
Thank-you
SQL 75

Similar Messages

  • PowerShell Script to Delete Files Based on Current Date

    I know by using Get-Date PowerShell will look at the current date.  I would like to make a very basic PS Script which will delete a file older than 8 days based on the current day.  I believe using a if/then function will be necessary. 
    I am very new to scripting so Im not sure how the syntax is written.  All help appreciated.

    Yes, use -Recurse to get subfolders too:
    $Folder = "C:\Users\Me\Backups"
    Get-ChildItem -Path $Folder -Recurse |
    Where { $_.LastWriteTime -lt [DateTime]::Today.AddDays(-8) } |
    Sort LastWriteTime |
    Remove-Item $_ -Force -Confirm:$false
    Sam Boutros, Senior Consultant, Software Logic, KOP, PA http://superwidgets.wordpress.com (Please take a moment to Vote as Helpful and/or Mark as Answer, where applicable) _________________________________________________________________________________
    Powershell: Learn it before it's an emergency http://technet.microsoft.com/en-us/scriptcenter/powershell.aspx http://technet.microsoft.com/en-us/scriptcenter/dd793612.aspx

  • How to delete Folders and Files older than 10 day ?

    If I use this below command, I am able to delete only the files and files in sub-folders older than 10 day,
    forfiles /p "D:\Testing\Sample" /s /d -10 /c "cmd /c del /s /q @file"
    Please help...
    Thanks

    Hello Raman459,
    please see this blog entry:
    http://elderec.org/2012/02/scripting-delete-files-and-folders-older-than-x-days/
    Your command is ok for files, for folders you need to do another command:
     forfiles -p "D:\Testing\Sample" -d -10 -c "cmd /c IF @isdir == TRUE rd /S /Q @path"
    If this post solved your question, please mark as an answer, or if it helped your quest, please vote as helpful. Thank you.
    Thank you,
    F. Schubert
    System Administrator
    MCP | Microsoft Certified Professional
    MCTS 70-640 | Microsoft Certified Technology Specialist: Windows Server 2008 Active Directory, Configuration
    MCTS 70-642 | Microsoft Certified Technology Specialist: Windows Server 2008 Network Infrastructure, Configuration
    MCTS 70-643 | Microsoft Certified Technology Specialist: Windows Server 2008 Applications Infrastructure, Configuring
    MCTS 70-680 | Microsoft Certified Technology Specialist: Windows 7, Configuration

  • Outlook 2013 Deletes mail older than 30 days in deleted items folder

    Environment: Outlook 2013 and Exchange 2007 (fully patched)
    One user has an issue where only 30 days worth of email is maintained in the deleted items folder. Every day, any email sent to deleted the previous day, will be gone.
    Any thoughts?

    Hi,
    Outlook itself doesn't auto-delete anything. It could be something that's automatically being done by the server.
    Let's first check the behavior on Outlook Web App (OWA), and see if issue persists.
    If issue repro's on OWA, then it's something on Exchange server side, I would suggest you post the question in
    Exchange server forum for further assistance.
    If issue doesn't repro on OWA side, it might be something on Outlook client side that deletes emails from the trash. For this scenario, I would suggest you first check if he/she has
    AutoArchive configured for the deleted folder which might delete messages older than a certain period of time.
    Please feel free to post back with any findings.
    Regards,
    Ethan Hua
    Forum Support
    Come back and mark the replies as answers if they help and unmark them if they provide no help.
    If you have any feedback on our support, please click
    here

  • Script to delete files created on a specific date with sepecific name

    Hi,
    Is it possible to help me with a powershell script that delete files under a folder and subfolders that have the following attributes
    1. have the name (default.*) and (index.*)
    2. created on a specific date say 1-9-2014
    3. created between specific time say between 10:00 - 16:00
    Thanks in advance!

    break out the components of the script.
    IE does this match 
    Get-ChildItem -Recurse c:\temp\*.*or Get-ChildItem -Recurse c:\temp\*.* | Where-Object {$_.CreationTime -gt (get-date "01-09-2014 10:00AM") -and $_.
    CreationTime -lt (get-date "01-09-2014 14:00PM")}Get-ChildItem -Recurse c:\temp\*.* | Where-Object {$_.CreationTime -gt (get-date "01-09-2014 10:00AM") -and $_.
    CreationTime -lt (get-date "01-09-2014 14:00PM")} | Where-Object {$_.name -match "default"}Might not be working as it might not be matching.Once you get it matching the remove-item will work.
    Cheers,
    Martin
    Blog:
    http://sustaslog.wordpress.com 
    LinkedIn:
    Note: Posts are provided “AS IS” without warranty of any kind, either expressed or implied, including but not limited to the implied warranties of merchantability and/or fitness for a particular purpose.

  • Powershell Command to permanently delete items in ALL users Deleted Items folder older than X days.

    Does anyone know a powershell command that can be run on Exchange 2010 SP1 that will permanently delete mail in the deleted items folder older than X days for ALL users in a specific database? This should include any user created subfolders in deleted items
    also.
    I know that seems bizarre to have user created subfolders in deleted items but we have found that users have discovered that if they create subfolders then their deleted items dont get purged at the regular retention period time.
    Thank You.

    Hi,
    For Exchange 2010 SP1, we can use search-mailbox and new-mailboxexportrequest to delete message in certain folder.
    Understanding Exchange Search
    http://technet.microsoft.com/en-us/library/bb232132.aspx
    Xiu Zhang
    TechNet Community Support

  • "A script that will delete perfstat snapshots older than 90 days with SPPURGE..."

    Hello to all my fine Oracle related friends...We are all one large extended Family...
    I want to create a script that will execute SPPURGE on Perfstat for snapshots that are older than 90 days.
    Now, I have Grid 12c Cloud Control up and running for all the Databases that we have...
    Should I use Grid 12c to execute the SPPURGE and just pass the parameters in like that?
    Or should I go "Old School" and make a Shell Script and schedule it in the crontab?
    What would you guys do?
    I want implement this for 41 "Standard Edition" Databases....some are "Data Guard".....
    Thanks,
    Xevv.

    Xevv Bellringer wrote:
    Hi Ed,
    I tried executing this manually and it's not deleting the snapshots at all.
    begin
    statspack.purge(trunc(sysdate-90),true);
    end;
    I even let it for an entire day and then altered the code like this...But when I execute it, it doesn't deleted the data..
    begin
    statspack.purge(trunc(sysdate-1),true);
    end;
    When I do a select sysdate -1 from dual; it gives the correct date?
    Could there be a "NLS Setting" some where causing this?
    How do you determine that it is not deleteding data?  (please show evidence)
    How, and how often, are you collecting a statspack snapshot?  (please show evidence)

  • Export -mailbox to move emails older than 400 days to pst file

    i have written the below script
    $date = get-date
    $MailboxList = get-content "E:\del_users.txt"
    ForEach ($Mailbox in $MailboxList) {
    Export-Mailbox -Identity $Mailbox -PSTFolderPath E:\pstfiles\$mailbox.pst -BadItemLimit 1000000 -StartDate $date.adddays(-450).ToString('MM/dd/yyyy') -DeleteContent
    my target is to move all emails older than 450 days to a pst file. i ran this on one user and noticed his emails from today to 450th day from today was moved out.
    In simple terms, i want to move all emails in all sub-folders that are older than 01-January-2014. Once this is done and when he logs to owa or outlook he must be only be able to see emails from 01-Jan-2014 to 17-Mar-2015.
    how can i achieve this with the above script?
    cheers

    We are facing this error with few mailboxes which are exclusively in one DB under one Storage Group & the mailbox is on EX001 with Exchange 2007 SP1
    We have 2 exchange servers:
    EX001 - Exchange 2007 SP1
    EX002 - Exchange 2007 SP3 (fully updated)
    I have setup a Windows 8.1 32bit machine with Outlook 2013 for running the export-mailbox cmdlet to export mails to a PST file
    We are facing this error with few mailboxes which are exclusively in one DB under one Storage Group & the mailbox is on EX001 with Exchange 2007 SP1
    We I run the below script, 
    $date = get-date
    $MailboxList = get-content "E:\del_users.txt"
    ForEach ($Mailbox in $MailboxList) {
    Export-Mailbox -Identity $Mailbox -PSTFolderPath E:\pstfiles\$mailbox.pst -BadItemLimit 1000000 -StartDate “01/01/2005" -EndDate “12/31/2013" -DeleteContent
    I get the below error, only from some users and not all users.
    Error was found for User ([email protected]) because: Error occurred in the step: Moving messages. Failed to copy messages to the destination mailbox store with error: 
    MAPI or an unspecified service provider.
    error code: -1056749164
    I went through the link: https://social.technet.microsoft.com/Forums/en-US/3c75a6db-74a4-484c-a7f4-5b411900d09b/exchange-2007-exportmailbox-error-message-on-only-certain-mailbox?forum=exchangesvrdeploylegacy 
    I understand this is a permission issue and i have tried all of the below
    1. The user doing the export is a member of local administrator group in both source and target machine.
    2. the user doing the export is granted the exchange administrator role on EMC in both the source and target machine.
    3. Given full access permission to the username moving the mailbox to PST
    4. given receive-as permission to the username moving the mailbox to pst
    5. Given genericall access to the DB
    6. Create a New User account (EX: ExportAdmin)
    Add this account to a Exchange Server Administrator Permission Both Source and Target Exchange Mailbox Server
    Add this account to Local Administrators Group Member Both Source and Target Exchange Mailbox Server
    Make sure this account DO NOT HAVE ANY Domain Admin/Exterprise Admin permission(Just keep Domain User group permission)
    Assign Mailbox Full Access to this account by follow Cmdlet
    Get-Mailbox -Server "EX-CCR" | Add-MailboxPermission -User ExportAdmin -AccessRights FullAccess
    Runas with ExportAdmin account (Open EMC)
    Get-Mailbox -Server "EX-CCR" | Export-Mailbox -PSTFolderPath
    Done
    7. On the DB, we set the retention to 0
    however none of the above has helped me resolve my issue.
    Please help me correct this

  • Need a script for archive/copy IMAP Emails older than 25 days to local mailbox

    Hi there,
    I am really troubling with archiving my IMAP mails. So far I was using standard rules, which have a major drawback - they only work on incoming mails. But I want to copy only mails to my local mailbox that are older than 25 days. The reason is that by copying all incoming mails, mail also copies all spam and unimportant mails into the local mailbox. However I only want to copy the mails that I was able to read and consider to be important, which I am able to do within a couple of days. However, I am not able to to that on a daily basis and that is why I chose the 25 days window, because my hoster deletes them automatically after 30 days. I read in a lot of forums that rules wont help, since they only work for incoming mails, therefore I am guessing that I would need a script because I want this to be automated and only applied to mails that passed the 25 day timeframe. Is the anybody that could help me out? Thank you so much in advance.

    Hi adayzdone,
    thanks for your reply but I am not a Gmail user, I am using Strato. Therefore the handy Google Scripts won't help.
    I need a script in Apple, that only copies or moves the mail from my inbox to a local mailbox once they are past the 25 days line. Within those 25 day I have deleted all unnessecary mails, marks or higlighted the important once and know only the remaining once are worth keeping. But I still want them to be available in Mail and none of those archiving solutions that create pdfs or import them into their one database will help.

  • Looking for help with PowerShell script to delete folders in a Document Library

    I'd like to create a PowerShell script to delete old folders in a Document library that are over 30 days old. Has anyone created something like this?
    Orange County District Attorney

    Hello Sid:
    I am trying to do the same and Iam running the script to delete the subfolders inside a folder  but I have some errors. 
    Could you please take a look?
    _______Script________
    $web = Get-SPWeb -Identity https://myportal.mydomain.com
    $list = $web.GetList("ar_mailingactivity")
    $query =  New-Object Microsoft.SharePoint.SPQuery 
    $camlQuery = '<Where><And><Eq><FieldRef Name="ContentType" /><Value Type="Computed">Folder</Value></Eq><Leq><FieldRef Name="Created" /><Value Type="DateTime"><Today OffsetDays="-30" /></Value></Leq></And></Where>'
    $query.Query = $camlQuery
    $items = $list.GetItems($query)
    for ($intIndex = $items.Count - 1; $intIndex -gt -1; $intIndex--)
       $items.Delete($intIndex);
    ________Errors_______
    Unable to index into an object of type System.Management.Automation.PSMethod.
    At C:\Script.ps1:2 char:22
    + $list =$webGetList <<<< "ar_mailingactivity"]
    + CategoryInfo
    :InvalidOperation: (ar_mailingactivity:String) [], RuntimeException
    + FullyQualifiedErrorID
    :CannotIndex
    You cannot call a method on  a null-valued expression.
    At c:\Script.ps1:6 char:24
    + $items = $list.GetItems <<<< ($query)
    + CategoryInfo
    :InvalidOperation: (GetItems:String) [], RuntimeException
    + FullyQualifiedErrorID
    :InvokeMethodOnNull

  • TS4002 Messages older than 30 days in inbox are not moved to deleted items when removed.

    I've had a few messages that were stored in my inbox and were older than 30 days. I've noticed that when I actually delete them they aren't moved to Deleted Items (and sat for 30 days before permanently deleted). It seems that the actual date of the email is being used to calculate the age and not the time it sits in deleted items.

    If deleted email isn't being moved to the trash you might want to go to icloud.com from your computer, open mail, click on the gear-shaped icon on the top right and choose preferences, then confirm on the General tab that you have checked "Move deleted messages to" and selected "Tash" from the drop-down list.

  • How to delete data older than three years from DSO

    Hi  all,
    We needs to keep historical data in the DSO only for three years. One way of doing this is by selective deletion we can delete data older than three years but we want to make it authomated. Is it possible to add a process or ABAP program to delete data older than three years.
    If it is p[ossible by ABAP code then can you please give me sample code.
    Many Thanks in advance.
    Harman

    Some time for in case of huge volume of data selective deletion is not works, Try for "prunning" option.
    It's work as follows
    1)     Create DSO which is same replica of your Source DSO.
    2)     Create two transformation
         a) from Source DSO to Copy DSO
         b) Another is from Copy DSO to Source DSO
    3)     Transprort Last 3 years records to Copy of Source DSO using DTP Filter range for time.
    4)     Once data loading from Source DSO to Copy DSO get completed delete all data from Source DSO.
    5)     Now load data from Copy DSO to Source DSO.
    6)     After complete loading delete entire data from Source DSO.
    I use prunning process to one of my client and it's work perfectly.
    Regards,
    Sushant
    +919820849482

  • Delete messages older than a date except personal folder

    Hello everyone,
    I have been spending a lot of time searching and testing how to delete all items older than 6 months in a user mailbox, but this rule it cannot be applied just one personal folder named "personal". I have been reading about retention policy and
    retention policy tags, but I can't figure out how to use that to keep all items older than 6 month in personal folder.
    could anyone tell me if I am right with retention policy or it's better other way?
    thank you in advice

    Hi,
    In Outlook client, we can set AutoArchive for all folders to delete all items older than 6 months except for “Personal” folder one by one.
    If you want to use retention policy in Exchange side, we can use retention tags and retention policies to have a try. there are three types of retention tags:
    Default policy tag (DPT), Retention policy tag (RPT), Personal tag.
    For your scenario, we can create a personal tag applied for this Personal folder. For example,
    delete messages older than 3 years for this personal folder. Then apply this personal tag for Personal folder in Outlook. And the Personal folder items are all tagged. After that, we can
    applying default policy tags (DPTs) to mailboxes to manage the retention of all untagged items.
    Personal suggestion, since the delete action is only used for one specific mailbox, I suggest we can use AutoArchive in Outlook side to achieve it.
    Regards,
    Please remember to mark the replies as answers if they help, and unmark the answers if they provide no help. If you have feedback for TechNet Support, contact [email protected]
    Winnie Liang
    TechNet Community Support
    Hi Winnie Liang,
    Thank you for answer. I would like to do all tasks from exchange side, so I know how to apply a retention policy to a mailbox for deleting all older than 6 months. But how can I apply the personal policy tag to a personal folder's users?
    All involved users in this requirement are warned that they must let all personal messages in "personal" folder named "personal".
    regards

  • HT3275 I've 1.85TB empty space on my time Machine, but it only backs up to the beginning of the previous month. it should have weekly back-ups for every month before that. Any ideas why it deletes stuff older than a month?

    I've 1.85TB empty space on my Time Machine, but it only retains back-ups to the beginning of the previous month. I should be able to access weekly back-ups for every month before that until the disk is full. Any ideas why it deletes stuff older than a month?
    Thanks, Rigby.

    If you are using Ethernet to connect your Mac to the Time Capsule, are you allowing at least 2-3 minutes for Time Machine to fully load when you open the application to see your backups?
    If you are using wireless to connect, you may need to allow 8-10 minutes or longer for everything to fully load, depending on the speed of your wireless connection.
    If you see only white time "bars" on the timeline at the right of the screen, you are seeing temporary backups. Permanent backups are displayed with purple "bars".

  • Query for deleting rows older than 25?

    Am trying to delete rows older than 25... How would the query for this be like? I tried this "DELETE FROM DB LIMIT 25,100" But getting errors...

    what is older than 25? Does it mean with id greater then 25?
    then you should have a query like
    DELETE FROM tableName WHERE id > 25

Maybe you are looking for