Script to delete user files older than 2 days

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>
ben1211Asked:
Who is Participating?
 
Dan CraciunConnect With a Mentor IT ConsultantCommented:
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
 
Scott ThomsonCommented:
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
 
ben1211Author Commented:
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
Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

 
Scott ThomsonCommented:
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
 
arnoldCommented:
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
 
Scott ThomsonCommented:
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
 
ben1211Author Commented:
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
 
ben1211Author Commented:
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
 
Scott ThomsonCommented:
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
 
arnoldCommented:
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
 
Scott ThomsonCommented:
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
 
ben1211Author Commented:
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
 
Scott ThomsonCommented:
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
 
Dan CraciunIT ConsultantCommented:
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
 
Scott ThomsonCommented:
Dan does that also exempt the 2 folders requested earlier..? admin and default..?
0
 
Dan CraciunIT ConsultantCommented:
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
 
Dan CraciunIT ConsultantCommented:
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
 
Scott ThomsonCommented:
pure brilliance.. :) good job
0
 
Dan CraciunIT ConsultantCommented:
Powershell makes it easy, and readable.
Now it remains to be seen if the OP can use PS...
0
 
ben1211Author Commented:
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
 
ben1211Author Commented:
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.