?
Solved

Simple delete folder script

Posted on 2013-02-05
7
Medium Priority
?
427 Views
Last Modified: 2013-03-11
Hello, I'm looking for a script .bat or .vbs (something that will easily work with task scheduler) that will delete a folder that is at least one day old (or anything but the current day) with a specific name. Here's my scenario.

I have many old anti-virus folders getting archived with the date as the folder name here are 3 folder I have currently in my directory and I would like to have a script that deletes the other two - I DO NOT WANT TO DELETE ANY OF THE OTHER FOLDERS IN THAT DIRECTORY. With the 3 folders below it would delete #'s 1. and 2.

1. 20130130 (Date modified 1/31)
2. 20130201 (Date modified 2/2)
3. 20130202 (Date modified 2/3)

I would like to run this script every morning, I'm assuming we can do something like (2013*) for the name piece?

THANKS!
0
Comment
Question by:jacksonwsa
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
  • 2
7 Comments
 
LVL 13

Expert Comment

by:Gabriel Clifton
ID: 38857633
I use this VB to delete "old" folders and use a batch script to call it. You could just call it from task scheduler or command prompt.
cscript "\\server\share$\deleteold.vbs" "path to root folder to check date eg \\server\share2" 14  <-- age of oldest folder you want to keep, 1 would be one day.

Dim oShell
Set oShell = CreateObject("Wscript.Shell")

forceUseCScript

Sub forceUseCScript()
   If Not WScript.FullName = WScript.Path & "\cscript.exe" Then
      oShell.Run "cmd.exe /k " & WScript.Path & "\cscript.exe //NOLOGO " & Chr(34) & WScript.scriptFullName & Chr(34),1,False
      WScript.Quit 0
   End If
End Sub


'option explicit

Call DoTheJob()
WScript.Echo "--- end of script execution ---"

Sub DoTheJob
    dim limitDate
    dim formattedLimitDate
    dim folder
    dim strComputer
    dim objWMIService
    dim colFileList
    dim objFile
    dim nbFiles
    dim totalFiles
    dim nbErrors
    dim result
    dim nbDays

    if WScript.Arguments.Count <> 2 then
        WScript.Echo "usage : DeleteOldFiles.vbs <folder> <nb of days ago>"
        WScript.Echo "sample: DeleteOldFiles.vbs C:\Windows\temp 90"
        Exit Sub
    end if

    folder = WScript.Arguments(0)
    nbDays = WScript.Arguments(1)

    'calculate and format limit date
    limitDate = DateAdd("d", -1 * nbDays , Date)

    formattedLimitDate = DatePart("yyyy", limitDate)

    if DatePart("m", limitDate) < 10 then
     formattedLimitDate = formattedLimitDate & "0"
    end if
    formattedLimitDate = formattedLimitDate & DatePart("m", limitDate)

    if DatePart("d", limitDate) < 10 then
     formattedLimitDate = formattedLimitDate & "0"
    end if
    formattedLimitDate = formattedLimitDate & DatePart("d", limitDate)

    'show what will be done
    WScript.Echo "Will remove files from " & folder & " with a date older than " & formattedLimitDate & " (" & nbDays & " days ago)"


    'Get the files and delete the old ones
    strComputer = "."

    Set objWMIService = GetObject("winmgmts:" _
        & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

    Set colFileList = objWMIService.ExecQuery _
        ("ASSOCIATORS OF {Win32_Directory.Name='" & folder & "'} Where " _
            & "ResultClass = CIM_DataFile")

    nbFiles = 0
    totalFiles = 0
    nbErrors = 0

    For Each objFile In colFileList
        totalFiles = totalFiles + 1
        if objFile.CreationDate < formattedLimitDate then
            
            result = objFile.Delete()
            
         WScript.Echo objFile.Name & " - " & objFile.CreationDate & ". Delete Result: " & result
         if result = 0 then
             nbFiles = nbFiles + 1
         else
             nbErrors = nbErrors + 1
         end if
        end if
    Next

    'Show the result
    Wscript.Echo "Total files in folder: " & totalFiles
    WScript.Echo "Deleted files:         " & nbFiles
    WScript.echo "Errors:                " & nbErrors
End Sub

Open in new window

0
 

Author Comment

by:jacksonwsa
ID: 38857648
This seems pretty complex for something this simple
0
 
LVL 13

Expert Comment

by:Gabriel Clifton
ID: 38857664
It is actually not complex. The code above is the vbscript that reads the date all of the folders in the root folder and deletes any "old" folders. This script can be permanent in that you create it once and and just change your calls whether by batch script, command line, or scheduled task to change your variables. I use this all of the time and it makes things super easy.

Example: I have the script on my desktop and I want to delete all folders in my mapped drive g: that are older than 10 days

cscript "%userprofile%\desktop\deleteold.vbs" "G:\" 10

or

Example 2: I have the script on my desktop and I want to delete all folders in my mapped drive g: in the folder test that are older than 21 days

cscript "%userprofile%\desktop\deleteold.vbs" "G:\test" 21
0
Supports up to 4K resolution!

The VS192 2-Port 4K DisplayPort Splitter is perfect for anyone who needs to send one source of DisplayPort high definition video to two or four DisplayPort displays. The VS192 can split and also expand DisplayPort audio/video signal on two or four DisplayPort monitors.

 
LVL 15

Expert Comment

by:Giovanni Heward
ID: 38857665
Hi, try this...

@echo off
setlocal enabledelayedexpansion
cd /d "%~dp0"
set mm=%date:~4,2%
set dd=%date:~7,2%
set yyyy=%date:~10,4%
set yy=%date:~12,2%
if exist !yyyy!!mm!!dd! echo Skipping !yyyy!!mm!!dd!
for /f %%f in ('dir /ad/od/b') do (
	if not %%f==!yyyy!!mm!!dd! (
		echo rd /s /q %%f
	)
)

Open in new window


Remove the echo in front of the rd /s /q %%f command if the output is the intended result.
0
 

Author Comment

by:jacksonwsa
ID: 38862489
OK, gotcha - thanks PantherTech. I'm going to test this tomorrow after I tried creating a few test folders.
0
 

Author Comment

by:jacksonwsa
ID: 38862512
Oh I don't know if you noticed my original comment, I also have to have it only select folders that begin with 2013... not just anything older than 1 day. Is there a way I can get that to work?
0
 
LVL 15

Accepted Solution

by:
Giovanni Heward earned 1500 total points
ID: 38876718
There's several ways to do that, here is one:

[example.bat]
@echo off
setlocal enabledelayedexpansion
cd /d "%~dp0"
set mm=%date:~4,2%
set dd=%date:~7,2%
set yyyy=%date:~10,4%
set yy=%date:~12,2%
if exist !yyyy!!mm!!dd! echo Skipping !yyyy!!mm!!dd!
for /f %%f in ('dir /ad/od/b !yyyy!*') do (
	if not %%f==!yyyy!!mm!!dd! (
		echo rd /s /q %%f
	)
) 

Open in new window


Note:  This is safe to run in it's current form.  Remove the echo in front of the rd /s /q %%f command once you've verified the output is your intended result.
0

Featured Post

Limited time offer using promo code EXPERTS30

Designed with a wealth of functionality and convenience, ATEN's new Thunderbolt™ 2 Sharing Switch takes your Thunderbolt setup to the next level. Now through September 15, 2017, Experts Exchange members get 30% off the US7220 on the ATEN USA eShop using promo code EXPERTS30.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article summaries thoughts and ideas from two years of sustained use. It provides good reasoning to make the jump to Windows 10.
The Windows functions GetTickCount and timeGetTime retrieve the number of milliseconds since the system was started. However, the value is stored in a DWORD, which means that it wraps around to zero every 49.7 days. This article shows how to solve t…
Windows 8 comes with a dramatically different user interface known as Metro. Notably missing from the new interface is a Start button and Start Menu. Many users do not like it, much preferring the interface of earlier versions — Windows 7, Windows X…
With the advent of Windows 10, Microsoft is pushing a Get Windows 10 icon into the notification area (system tray) of qualifying computers. There are many reasons for wanting to remove this icon. This two-part Experts Exchange video Micro Tutorial s…

765 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question