Need a script

I am looking for a script to delete files from a folder that are 5 days old. The script when deletes it has to create a log file that contains the name of the files that are deleted. The log file name should be the date whenever the script runs? Thanks
jmohan0302Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

NVITEnd-user supportCommented:
Here's a DelOld.bat version.
Adjust as needed...
- Path in FNLog . I used c:\local
- DaysOld
set Stamp=%DATE:~-4%%DATE:~-10,2%%DATE:~-7,2%
set Stamp=%Stamp: =0%
set FNLog=c:\local\%~n0_%Stamp%.log
set DaysOld=5
set Dir=%1
set Files=%2
>> "%FNLog%" echo %date% %time% BEGIN
pushd %Dir%
forfiles /d -%DaysOld% /p %Dir% /m %Files% /s /c "cmd /c del @path& if not exist @path echo Deleted @path>>%FNLog%"
popd
>> "%FNLog%" echo %date% %time% END

Open in new window


To run:
DelOld "c:\testdir" "*.*"

Open in new window

jmohan0302Author Commented:
Thanks NVIT....

 Could you please explain the script and let me know where I have to provide the path in the script. Thanks
jmohan0302Author Commented:
When I ran this I am getting the following output and it didn't delete the file... I think I am running it wrong. Also I want to know will the log file contains the files that are getting deleted.

Below is the output of the command

Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\Windows\system32>d:

D:\>A.bat

D:\>set Stamp=20151027

D:\>set Stamp=20151027

D:\>set FNLog=E:\DOCS\A_20151027.log

D:\>set DaysOld=5

D:\>set Dir=

D:\>set Files=

D:\>echo Tue 10/27/2015 22:59:35.79 BEGIN 1>>"E:\DOCS\A_20151027.log"

D:\>pushd

D:\>forfiles /d -5 /p  /m  /c "cmd /c del @path& if not exist @path echo Deleted
 @path>>E:\DOCS\A_20151027.log"
ERROR: Invalid syntax. Value expected for '/p'.
Type "FORFILES /?" for usage.

D:\>popd

D:\>echo Tue 10/27/2015 22:59:35.89 END 1>>"E:\DOCS\A_20151027.log"

D:\>
Making Bulk Changes to Active Directory

Watch this video to see how easy it is to make mass changes to Active Directory from an external text file without using complicated scripts.

Nadav SolomonCommented:
Powershell:
$olderThan = 5
$path = "c:\temp"
$logfile = "c:\temp\$((Get-Date).ToShortDateString().Replace("/",".")).txt"
#change to $true to delete
$deleteMode = $false 
############################################################

dir $path -File| %{
    $fileName = $_.FullName
    if((New-TimeSpan -Start $($_.CreationTime) -End $(get-date)).Days -gt $olderThan)
    {
        Add-Content -path $logfile -Value "Deleting $fileName"
        if($deleteMode)
        {
            $_.Delete()
        }
    }
}

Open in new window

NVITEnd-user supportCommented:
example:
If you want your log to end up in c:\, change it to:
set FNLog=c:\%~n0_%Stamp%.log

Open in new window


To adjust how many days old (and older) files to delete, change 5 to a number.
IMPORTANT: Using 0 will erase ALL FILES
set DaysOld=5

Open in new window

jmohan0302Author Commented:
Dear NVIT,

I want to know in the script where I have to provide the path. My requirement is the script has to delete only the files that 5 days old in a particular folder. Thanks
NVITEnd-user supportCommented:
> I think I am running it wrong
1. Open a CMD window.

2. Type the command. Change the path and file pattern as needed.
You have to specify the path and file pattern.
Be sure to wrap each with double-quotes. e.g. to erase all TXT files in c:\testdir...
DelOld "c:\testdir" "*.txt"

Open in new window


If you want to hard-code it so you don't have to specify the path and file pattern, let me know.
jmohan0302Author Commented:
Hi Nadav Solomon,

I am getting following error when I ran the script:

PS D:\Test> D:\Test\a.ps1
Get-ChildItem : A parameter cannot be found that matches parameter name 'File'.
At D:\Test\a.ps1:8 char:16
+ dir $path -File <<<< | %{
    + CategoryInfo          : InvalidArgument: (:) [Get-ChildItem], ParameterBindingException
    + FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
NVITEnd-user supportCommented:
This will delete all files in c:\testdir that 5 days and older.
The log is placed in your %temp% folder

Note: Change c:\testdir to your needs:
set Stamp=%DATE:~-4%%DATE:~-10,2%%DATE:~-7,2%
set Stamp=%Stamp: =0%
set FNLog=%temp%\%~n0_%Stamp%.log
set DaysOld=5
set Dir="c:\testdir"
set Files="*.*"
>> "%FNLog%" echo %date% %time% BEGIN
pushd %Dir%
forfiles /d -%DaysOld% /p %Dir% /m %Files% /s /c "cmd /c del @path& if not exist @path echo Deleted @path>>%FNLog%"
popd
>> "%FNLog%" echo %date% %time% END

Open in new window

jmohan0302Author Commented:
Hi NVIT,

I could not follow it up properly. Just provide the script for this example:

Say the path is E:\docs
The docs folder contains some files and folders that are 5 days old. I want a script to delete only the files from the path E:\docs and not the folders. The script has to generate the log file and it should contain the name of the files the script is deleting.  The name of the log file should be the date when the script runs?
Thanks for your help
Bill PrewIT / Software Engineering ConsultantCommented:
Here is a small VBS script that could do the job, save as a VBS and then run like this from a command prompt or BAT file:

cscript EE28781820.vbs

Const ForWriting = 2

' Define files and folders to process
strBaseDir = "C:\Temp\Files"
intAgeDays = 5

' Name log file with todays date and time (YYYYMMDD_hhmmss)
strDateStamp = Year(Now) & Right("0" & Month(Now), 2) & Right("0" & Day(Now), 2) & "_" & Right("0" & Hour(Now), 2) & Right("0" & Minute(Now), 2) & Right("0" & Second(Now), 2)
strLogName = "C:\Temp\log-" & strDateStamp & ".txt"

' Define filesystem object
Set objFSO = CreateObject("Scripting.FileSystemObject")

' Open the log file
Set objLog = objFSO.OpenTextFile(strLogName, ForWriting, True)

' Delete old files
For Each objFile in objFSO.GetFolder(strBaseDir).Files
   ' Check it's age, see if ready to delete
   If DateDiff("d", objFile.DateLastModified, Now) > intAgeDays Then
       ' Old enough, log it and delete it
       objLog.WriteLine "DELETE File:[" & objFile.Path & "], Age:[" & DateDiff("d", objFile.DateLastModified, Now) & "] days"
       objFile.Delete
   End If
Next

' Close log file, release objects
objLog.Close()

Open in new window

~bp
Bill PrewIT / Software Engineering ConsultantCommented:
And if you can use a small utility, one of my favorites is DELAGE32, take a look here:

http://www.horstmuc.de/wbat32.htm
http://www.horstmuc.de/win/delage.htm

~bp
NVITEnd-user supportCommented:
Revised for E:\docs
set Stamp=%DATE:~-4%%DATE:~-10,2%%DATE:~-7,2%
set Stamp=%Stamp: =0%
set FNLog=%temp%\%~n0_%Stamp%.log
set DaysOld=5
set Dir="E:\docs"
set Files="*.*"
>> "%FNLog%" echo %date% %time% BEGIN
pushd %Dir%
forfiles /d -%DaysOld% /p %Dir% /m %Files% /s /c "cmd /c del @path& if not exist @path echo Deleted @path>>%FNLog%"
popd
>> "%FNLog%" echo %date% %time% END

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
jmohan0302Author Commented:
Hi NVIT,

Thanks a lot. I got it. One more thing is that the script deletes the files that are older than 5 days from the path.  It also deletes the files that are older than 5 even in the sub folders in the path as well. If I want to delete only the files from the parent folder and not subfolder mean how to do that. Thanks
NVITEnd-user supportCommented:
Revised to delete only files in parent folder.
set Stamp=%DATE:~-4%%DATE:~-10,2%%DATE:~-7,2%
set Stamp=%Stamp: =0%
set FNLog=%temp%\%~n0_%Stamp%.log
set DaysOld=5
set Dir="E:\docs"
set Files="*.*"
>> "%FNLog%" echo %date% %time% BEGIN
pushd %Dir%
forfiles /d -%DaysOld% /p %Dir% /m %Files% /c "cmd /c del @path& if not exist @path echo Deleted @path>>%FNLog%"
popd
>> "%FNLog%" echo %date% %time% END

Open in new window

Mal OsborneAlpha GeekCommented:
Very easy if you have Server 2008 / Vista or later, with the forfiles command. Below is the contents of a batch file I wrote to preform a similar task:

forfiles -p "E:\Data\PFS\KyoceraScan" -s -m *.* /D -7 /C "cmd /c del @path"
jmohan0302Author Commented:
Hi NVIT,

Thanks it works fine both the scripts. I just like to know when compare both the scripts , (I mean to delete all the files in subfolders and only in Parent folder) seems the same. Could you please let me know where is the difference in script. Thanks a lot for your help
NVITEnd-user supportCommented:
Line 9. To delete subfolders, I add the /s switch.
That's the only difference.
jmohan0302Author Commented:
Hi NVIT,

Thanks a lot.

Is it possible to modify the script to move / archive  the 5 days files to another location and the log should provide the information about the files that are being moved and it would be better if it provides along with the  destination location as well.
jmohan0302Author Commented:
Hi NVIT,

Thanks I have modified the script by using move command. It works fine... I just want to know if I want to move the files along with the folders then how the script has to be modified. Thanks
NVITEnd-user supportCommented:
> ...move the files along with the folders
Do you want to move the folder the file resides in? If so, is it possible that non-qualifying files, i.e. with different dates might be in the same folder? Moving the folder would move those files, too.
jmohan0302Author Commented:
Hi Nvit,

Thanks.
Is it possible to modify the script to send the log files to email, thanks
NVITEnd-user supportCommented:
No need to move?
jmohan0302Author Commented:
Hi NVIT,

I am asking that the script is generating the log file right, I would like to modify the script at the end once all the files are deleted and after the log file is generated, is it possible to attach the log file as an attachment and can it be send it to selected recipients via script. Is it possible???
NVITEnd-user supportCommented:
Using the same .bat file, yes.
Download BLAT or similar command line mailer.
BLAT would be used to mail the log.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
VB Script

From novice to tech pro — start learning today.