Announcement

Collapse
No announcement yet.

Delete files based on age

Collapse
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Delete files based on age

    hi I looking for a simple script that I can setup with windows scheduler that it will find files over the age of 5 days and delete them from 1 folder.

    I Don't wish it to go deeper or higher just within that folder

    IE the folder name is "Scans" holding scanned pdfs it also has a sub folder called "peter" which Is for the director. hell have no fury if I delete thing inside his folder hahaha

    so I just want it to check the scanned folder delete any thing over 5 days without effecting "peter" folder

    found some interesting scripts and programs but none that do what I need sadly.

  • #2
    Re: Delete files based on age

    What is the OS of the computer where you like to schedule the task on? Is the Scans folder on this computers or, should the scheduled script run against a remote computer?


    If the computer has PowerShell and the folder is on the same computer you can try this script:

    Code:
    # scheduled task
    # launch: powershell.exe
    # args: -executionpolicy ByPass -file "c:\myscripts\clearScanfolder.ps1" RUN
    # ----------------------------------------------------------------------------
    
    
    # if ($Args.Count -eq 0) {exit 1}
    
    $Scanfolder = "D:\Scans"
    $LastWrite = (Get-Date).AddDays(-5)
    
    $Files = Get-ChildItem $Scanfolder -EA Stop | where {$_.LastWriteTime -lt $LastWrite -and !$_.psiscontainer}
    if (($files | measure).Count -gt 0) {foreach ($File in $Files) {
       write-host Deleting: """$File"""
       Remove-Item -LiteralPath $File.fullname -force
    }} ; write-host ($files | measure).Count files deleted from """$Scanfolder"""
    Add a scheduled job.
    At tab 'Actions' / the program to execute is: powershell.exe
    The Arguments you should add are: -executionpolicy ByPass -file "c:\myscripts\clearScanfolder.ps1" RUN
    (you may have to adjuste the above script folder and name of the file)

    The last argument RUN is not required.
    If you would uncomment the line if ($Args.Count -eq 0) {exit 1} in the script and use that last argument 'RUN' - you can prevent files from being deleted when the script accidentally is started manually.

    /Rems

    This posting is provided "AS IS" with no warranties, and confers no rights.

    __________________

    ** Remember to give credit where credit's due **
    and leave Reputation Points for meaningful posts

    Comment


    • #3
      Re: Delete files based on age

      ok I modified the file to point to the correct location but got some questions if I can

      the folder in question is
      D:\data\resources\Scans

      but I also have a folder in this folder called pete so
      D:\data\resources\Scans\pete

      will this also delete files older then 5 days from petes folder as well?

      rather they did not if possible.



      Code:
      # scheduled task
      # launch: powershell.exe
      # args: -executionpolicy ByPass -file "c:\myscripts\clearScanfolder.ps1" RUN
      # ----------------------------------------------------------------------------
      
      
      # if ($Args.Count -eq 0) {exit 1}
      
      $Scanfolder = "D:\data\resources\Scans"
      $LastWrite = (Get-Date).AddDays(-5)
      
      $Files = Get-ChildItem $Scanfolder -EA Stop | where {$_.LastWriteTime -lt $LastWrite -and !$_.psiscontainer}
      if (($files | measure).Count -gt 0) {foreach ($File in $Files) {
         write-host Deleting: """$File"""
         Remove-Item -LiteralPath $File.fullname -force
      }} ; write-host ($files | measure).Count files deleted from """$Scanfolder"""

      Comment


      • #4
        Re: Delete files based on age

        Originally posted by Mandrake View Post
        ok I modified the file to point to the correct location but got some questions if I can

        the folder in question is
        D:\data\resources\Scans

        but I also have a folder in this folder called pete so
        D:\data\resources\Scans\pete

        will this also delete files older then 5 days from petes folder as well?

        rather they did not if possible.
        The script does not delete files from petes folder or any sub folder.

        You can test the scheduled script by temporary change the defined target folder to a folder that is a copy of the scans folder. Copy the content of the scans folder to the test folder.

        /Rems

        This posting is provided "AS IS" with no warranties, and confers no rights.

        __________________

        ** Remember to give credit where credit's due **
        and leave Reputation Points for meaningful posts

        Comment


        • #5
          Re: Delete files based on age

          when I excute this in power shell it works fine but when I try and do it with scheduled task as u advise something dose not work

          this is the error I get


          Log Name: Microsoft-Windows-TaskScheduler/Operational
          Source: Microsoft-Windows-TaskScheduler
          Date: 14/07/2014 10:34:45 AM
          Event ID: 101
          Task Category: Task Start Failed
          Level: Error
          Keywords: (1)
          User: SYSTEM
          Computer: FileServ.lce.internal
          Description:
          Task Scheduler failed to start "\Scans Auto Delete" task for user "LCE0\Administrator". Additional Data: Error Value: 2147943785.
          Event Xml:
          <Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
          <System>
          <Provider Name="Microsoft-Windows-TaskScheduler" Guid="{DE7B24EA-73C8-4A09-985D-5BDADCFA9017}" />
          <EventID>101</EventID>
          <Version>0</Version>
          <Level>2</Level>
          <Task>101</Task>
          <Opcode>101</Opcode>
          <Keywords>0x8000000000000001</Keywords>
          <TimeCreated SystemTime="2014-07-14T00:34:45.832622900Z" />
          <EventRecordID>136413</EventRecordID>
          <Correlation />
          <Execution ProcessID="684" ThreadID="9512" />
          <Channel>Microsoft-Windows-TaskScheduler/Operational</Channel>
          <Computer>FileServ.lce.internal</Computer>
          <Security UserID="S-1-5-18" />
          </System>
          <EventData Name="TaskStartFailedEvent">
          <Data Name="TaskName">\Scans Auto Delete</Data>
          <Data Name="UserContext">LCE0\Administrator</Data>
          <Data Name="ResultCode">2147943785</Data>
          </EventData>
          </Event>

          Comment


          • #6
            Re: Delete files based on age

            Usually you get error Event 101 when you have configured that the job should only run when the configured account (in your case the SYSTEM acount I see) is logged-in. Change that setting to "Run Task Whether Account Is Logged on Or Not"

            If that does not help, then export the scheduledtask and post the content of the XML file here.


            /Rems

            This posting is provided "AS IS" with no warranties, and confers no rights.

            __________________

            ** Remember to give credit where credit's due **
            and leave Reputation Points for meaningful posts

            Comment


            • #7
              Re: Delete files based on age

              hi rems thank you a lot for you constant help I hope we can nail this down

              ok as to the run wither logged on or off I already did this in original setup as I thought it would be a issue down the track any way. so that's already done


              so here is the xml file output for the task

              Code:
              <?xml version="1.0" encoding="UTF-16"?>
              <Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
                <RegistrationInfo>
                  <Date>2014-07-14T10:20:37.6155051</Date>
                  <Author>LCE0\administrator</Author>
                </RegistrationInfo>
                <Triggers>
                  <CalendarTrigger>
                    <StartBoundary>2014-07-15T08:00:00</StartBoundary>
                    <Enabled>true</Enabled>
                    <ScheduleByDay>
                      <DaysInterval>1</DaysInterval>
                    </ScheduleByDay>
                  </CalendarTrigger>
                </Triggers>
                <Principals>
                  <Principal id="Author">
                    <UserId>LCE0\administrator</UserId>
                    <LogonType>Password</LogonType>
                    <RunLevel>HighestAvailable</RunLevel>
                  </Principal>
                </Principals>
                <Settings>
                  <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
                  <DisallowStartIfOnBatteries>true</DisallowStartIfOnBatteries>
                  <StopIfGoingOnBatteries>true</StopIfGoingOnBatteries>
                  <AllowHardTerminate>true</AllowHardTerminate>
                  <StartWhenAvailable>true</StartWhenAvailable>
                  <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
                  <IdleSettings>
                    <StopOnIdleEnd>true</StopOnIdleEnd>
                    <RestartOnIdle>false</RestartOnIdle>
                  </IdleSettings>
                  <AllowStartOnDemand>true</AllowStartOnDemand>
                  <Enabled>false</Enabled>
                  <Hidden>false</Hidden>
                  <RunOnlyIfIdle>false</RunOnlyIfIdle>
                  <WakeToRun>false</WakeToRun>
                  <ExecutionTimeLimit>P3D</ExecutionTimeLimit>
                  <Priority>7</Priority>
                </Settings>
                <Actions Context="Author">
                  <Exec>
                    <Command>C:\Windows\WinSxS\wow64_microsoft-windows-powershell-exe_31bf3856ad364e35_6.2.9200.16384_none_cc34506ac0579b76\powershell.exe</Command>
                    <Arguments>-executionpolicy ByPass -file "c:\script\clearScanfolder.ps1"</Arguments>
                  </Exec>
                </Actions>
              </Task>

              Comment


              • #8
                Re: Delete files based on age

                why is it btw the computer name is: FileServ.lce.internal and the user name is: LCE0\administrator?? (server is in LCE and user is in LCE0) Is the netbios name of your AD domain not matching the second-level of the dns name of the domain, or do you have multiple domains?, or is it a local account from an other computer?
                Can you create a service account (a local account that is a member of the local group administrators OR a domain account that is member of the domain admins group in the same domain as where the computer is in). And then configure that service account to run the task.
                'Run with highest privileges' was checked, that is good.

                The user that is configured to run this scheduled task must have "Log on as a batch job" rights on the computer.


                I noticed that the <Enabled> state is set to false, make sure the job is Enabled when you start the test.
                The job is scheduled at 8:00 am, make sure the computer is powered on that time.

                Why you running powershell.exe from path "C:\Windows\WinSxS\wow64_microsoft-windows-powershell-exe_31bf3856ad364e35_6.2.9200.16384_none_cc34506ac 0579b76".
                The path of the exexcutable is"%SystemRoot%\system32\WindowsPowerShell\v1.0\ ". But you actually don't have to enter the path.

                What version of powershell is installed? check version:http://blogs.technet.com/b/heyscript...hell-runs.aspx

                Check the powershell script for typo's and that it is saved as "clearScanfolder.ps1" in folder c:\script locally on the computer.

                Because there is no additional parameter provided on the command line,, the line: # if ($Args.Count -eq 0) {exit 1} should in your case begin with a hash (or, deleted entirely from the script).


                /Rems
                Last edited by Rems; 16th July 2014, 18:51.

                This posting is provided "AS IS" with no warranties, and confers no rights.

                __________________

                ** Remember to give credit where credit's due **
                and leave Reputation Points for meaningful posts

                Comment


                • #9
                  Re: Delete files based on age

                  ok ran it with local admin and it works a treat.

                  as to the other I am absolutely not sure why it is coming with the lce.inertnal part

                  I came in after this was all setup.

                  when I migrated to new OS sadly this problem stayed

                  well now that I sorted this out I shall go alooking for how to fix that hahaha


                  I must thank you a lot for your help. I glad that stuck around thru the process of getting it working
                  Last edited by Mandrake; 16th July 2014, 00:25.

                  Comment

                  Working...
                  X