Script to delete all files in a folder except locked files

aptnrickard
aptnrickard used Ask the Experts™
on
I need to write a batch file (or script) that I can schedule to run on one of our servers each day at 6 AM.

The batch command I was looking at is:  del c:\windows\temp\*.* /f /s /q

This works except it errors out when it comes across a locked file.

I need it to skip the file and continue deleting the others.

I'm pretty sure it's possible but I can't figure out how.

Cheers
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Try this:

robocopy C:\emptyfolder c:\windows\temp /MIR /R:0

If it comes to an error such as a locked file, it will skip it without hesitation.

Author

Commented:
Thank you, I never would have even thought of using robocopy.

I did a couple of quick tries here and this looks to do exactly what I was looking for.  I need to test a touch more as this will go on a live server but I think it will work.

Cheers
Robocopy is my favorite command line tool!

You're welcome.
Acronis in Gartner 2019 MQ for datacenter backup

It is an honor to be featured in Gartner 2019 Magic Quadrant for Datacenter Backup and Recovery Solutions. Gartner’s MQ sets a high standard and earning a place on their grid is a great affirmation that Acronis is delivering on our mission to protect all data, apps, and systems.

Commented:
Try:

cd /d c:\windows\temp
rd .  /s /q

That will try and delete all files and all dirs under c:\windows\temp - by being in the dir already it can't remove the temp directory itself, which is what you want.

Steve

Commented:
Blimey that was a quick one, yes robocopy is useful for all sorts :-)
@dragon-it: Very impressive stats on MS-DOS!

Commented:
Thanks, was where most windows scripting used to be posted rather than real MS-DOS mind, haven't touched that for a few years thankfully!

430,000 points this MONTH yourself too!?  That's some serious EE'ing!

Steve
I have high respect for command-line gurus. I try to do everything CL versus the GUI.

Thanks for kudos. Trying to break 500K before the end of this month. Very slim pickings today though.

Jesse

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial