?
Solved

Script to delete user files older than 2 days

Posted on 2014-04-01
21
Medium Priority
?
975 Views
Last Modified: 2014-04-28
Hi! I need help with a VB Script or Command Prompt script that deletes files from users profiles on the server every 2 days

The users RDP to these servers and have their own profiles. They save certain files in there, which they shouldn't be doing. As such, I need help with a script that deletes all files from each user profile on these servers.

The script should check for files that are older than 2 days old and delete files older than 2 days old.

These are the areas that the files need to be deleted from.  <username> is the user login profile.

Can this be done?

The structure on the server
C:\Users\<username>\Desktop
C:\Users\<username>\Downloads
C:\Users\<username>\Documents
C:\Users\<username>
0
Comment
Question by:ben1211
[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
  • 8
  • 6
  • 5
  • +1
21 Comments
 
LVL 10

Expert Comment

by:Scott Thomson
ID: 39971205
So just to confirm you want to
delete "files" not folders.
and only files within these 4 folders (under the users username profile)
that are older than 2 days..?

leaving the profiles and the folders in tact.
0
 

Author Comment

by:ben1211
ID: 39971206
So just to confirm you want to
delete "files" not folders.
and only files within these 4 folders (under the users username profile)
that are older than 2 days..?

leaving the profiles and the folders in tact.

yes correct
0
 
LVL 10

Expert Comment

by:Scott Thomson
ID: 39971217
Something like this should do it..

forfiles -p "<Folder Name>" -s -m *.* /D -<number of days> /C "cmd /c del @path"

Open in new window


Example,

          forfiles -p "C:\Temp" -s -m *.* /D -14 /C "cmd /c del @path"
**This example assumes C:\temp and 14 days**
     

P.S. This command line will also remove files (older than specified days) inside subfolders.
0
Will your db performance match your db growth?

In Percona’s white paper “Performance at Scale: Keeping Your Database on Its Toes,” we take a high-level approach to what you need to think about when planning for database scalability.

 
LVL 79

Expert Comment

by:arnold
ID: 39971219
Using filesystemobject you can scan and go through the directory structure looking files and their createddate or datelastmodified date

http://msdn.microsoft.com/en-us/library/6tkce7xa(v=vs.84).aspx

There are unix utilities that add the find command which can more easily run and locate files older ..

Note there is a significant risk to deleting files as you intend.  While I understand the reasoning, it is inevitable as your experience illustrated that people are still storing files that they should not and an age based election could and likely would delete a file that a user forgot to copy back after the changes.
0
 
LVL 10

Expert Comment

by:Scott Thomson
ID: 39971222
It might also be worth asking why you want to delete these files.? are you low on space or you just think deleting the files of 1 or 2 users will teach them not to do it?
0
 

Author Comment

by:ben1211
ID: 39971357
we need to clear space from these users directories. These are servers that users RDP in to do work, but shouldn't save any files on these servers. They are saving files here and the drive gets filled up quickly
0
 

Author Comment

by:ben1211
ID: 39971378
C:\Users\<username>\Desktop
C:\Users\<username>\Downloads
C:\Users\<username>\Documents
C:\Users\<username>

The <username> stated here are user's profiles

forfiles -p "<Folder Name>" -s -m *.* /D -<number of days> /C "cmd /c del @path"

will this script delete files from all users?

I would like to avoid deleting the Administrators Folder and the Default
0
 
LVL 10

Expert Comment

by:Scott Thomson
ID: 39971402
Yes this particular script will take ALL files in ALL subdirectories and blow them away.. i'll redo the script to avoid default and admin..
0
 
LVL 79

Expert Comment

by:arnold
ID: 39971429
If you have the options, you may want to setup a terminal server folder redirection to offload these files to a fileshare. This way the only thing that will remain on the RDP server are the user profile files which are significantly smaller though make sure that you do not have users using outlook since the .pst file is by default stored in the %userprofile%\local settings which could pose a data loss risk if you ever go to a roaming profile.

There are many examples available  via a search "vbscript directory traversing"
Those will illustrate the use of the filesystemobject navigating a directory

defining a function that can function as a recursive.
i.e. check if the named entry is a directory, if it is, list(directoryname)
datelastmodify note the way filename objects are assigned.
obj.lastmodifieddate will be the value of the date on which the file was last modified.  at times converting it to string might be necessary or performing date operations to assess whether it is older than x days.
0
 
LVL 10

Expert Comment

by:Scott Thomson
ID: 39971461
is it ok for the script to delete the whole user profile folder..? barring admin and default user of course. because deleting all files under the folders would do the same thing

and its easier to script ;)

If so then here is the answer (you will need to download Forfiles for this to work.)

***********************************
At first, make a text file with the folder exceptions, put one folder per line in double quotes.

 Put the exception file in your %userprofile% folder.
 example exception.txt:
"Default"
"Default User"
"All Users"



Batch code:
for /f "delims=" %%a in ('forfiles /p "%userprofile%\.." /d -180 /c "cmd /c if @isdir==TRUE echo @file"^|findstr /vig:"%userprofile%\exception.txt"') do echo rd /s /q "%%~a"

Open in new window

0
 

Author Comment

by:ben1211
ID: 39971480
hi Scott,

I can't delete the whole user profile. We found out that after deleting the entire user profile folder, the next time the user logs in, that particular user profile folder is not created. This is something we found out.

That's the reason why we can't delete the user profile folder
0
 
LVL 10

Expert Comment

by:Scott Thomson
ID: 39971483
ahh damn.. ok let me keep trying. but scripting is not "my thing" so ill have to steal from others to get what I want for you.. stay tuned. ^_^
0
 
LVL 35

Expert Comment

by:Dan Craciun
ID: 39971587
If you can use something more modern, here's a solution using Powershell:
gci C:\Users -File -Recurse | ?{$_.Directory -notmatch "C:\\Users\\Administrators.*|C:\\Users\\Default.*"} | ?{$_.LastWriteTime -lt (Get-Date).AddDays(-2)} | Remove-Item

Open in new window

I think the -File switch is only available since PS 3, so if you have a lower version let me know to modify the script.

This will only delete the files, not folders, so you won't need to recreate the folder structure and you'll get back the disk space.

HTH,
Dan
0
 
LVL 10

Expert Comment

by:Scott Thomson
ID: 39971591
Dan does that also exempt the 2 folders requested earlier..? admin and default..?
0
 
LVL 35

Expert Comment

by:Dan Craciun
ID: 39971599
Yup. In english, my script does the following:
gci C:\Users -File -Recurse - get all files inside the C:\users folder
then
?{$_.Directory -notmatch "C:\\Users\\Administrators.*|C:\\Users\\Default.*"} - select only the files with a path that does not start with C:\Users\Administrators or C:\Users\Default
then
?{$_.LastWriteTime -lt (Get-Date).AddDays(-2)} - select only the files with a date older than the other day
then
Remove-Item - delete those files.

PS: The administrative folder is called Administrator or Administrators?
0
 
LVL 35

Expert Comment

by:Dan Craciun
ID: 39971601
For safety, modify the script as follows:
gci C:\Users -File -Recurse | ?{$_.Directory -notmatch "C:\\Users\\Administrator.*|C:\\Users\\Default.*"} | ?{$_.LastWriteTime -lt (Get-Date).AddDays(-2)} | Remove-Item

Open in new window

Note that I removed the s from "Administrators", so now the script won't touch any files with a path that starts with C:\Users\Administrator. This includes folders called C:\Users\Administrators
0
 
LVL 10

Expert Comment

by:Scott Thomson
ID: 39971648
pure brilliance.. :) good job
0
 
LVL 35

Expert Comment

by:Dan Craciun
ID: 39971677
Powershell makes it easy, and readable.
Now it remains to be seen if the OP can use PS...
0
 

Author Comment

by:ben1211
ID: 39973917
Dan, how do I run PowerShell.

I need to run this script on Windows 2008 R2.

Do I just paste your script gci C:\Users -File -Recurse | ?{$_.Directory -notmatch "C:\\Users\\Administrator.*|C:\\Users

into a text file, or do I run it from command prompt?

Can I schedule this script?
0
 

Author Comment

by:ben1211
ID: 39973921
hi Dan,

I was checking on the version, which I don't understand. This is what I get:

PS C:\> $PSVersionTable.PSVersion

Major  Minor  Build  Revision
-----  -----  -----  --------
2      0      -1     -1
0
 
LVL 35

Accepted Solution

by:
Dan Craciun earned 2000 total points
ID: 39974034
That means you're on Powershell v2, the version that came with Windows 2008.

If you're on Win 2008 R2 SP1, you can just update to PS v3 using Windows Update or from here: https://www.microsoft.com/en-us/download/details.aspx?id=34595

If not, here's a script that should work in PS v2:
gci C:\Users -Recurse | ?{!$_.PSisContainer} | ?{$_.Directory -notmatch "C:\\Users\\Administrator.*|C:\\Users\\Default.*"} | ?{$_.LastWriteTime -lt (Get-Date).AddDays(-2)} | Remove-Item

Open in new window

You run it by pasting the line in Powershell console (Start->Run->type Powershell->press Enter) or by saving the code into a file with the extension .ps1 and then right-clicking the file and selecting "Run with Powershell".

You're probably going to get an error that PS scripts are disabled on your system (the default). To get past that, run this in PS console:
Set-ExecutionPolicy RemoteSigned

Open in new window

This means: run all locally created scripts and run scripts downloaded from the Internet only if they are digitally signed.
0

Featured Post

Learn how to optimize MySQL for your business need

With the increasing importance of apps & networks in both business & personal interconnections, perfor. has become one of the key metrics of successful communication. This ebook is a hands-on business-case-driven guide to understanding MySQL query parameter tuning & database perf

Question has a verified solution.

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

If you use Adobe Reader X it is possible you can't open OLE PDF documents in the standard. The reason is the 'save box mode' in adobe reader X. Many people think the protected Mode of adobe reader x is only to stop the write access. But this fe…
Determining the an SCCM package name from the Package ID
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…
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…
Suggested Courses

777 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