4

I have a folder being filled with auto generated files by an application. There are csv and png extensions being created and stored in there. We need to delete all files in the folder except certain png files where the filename starts with "abc-". The system is a windows server 2012 r2 box, and the goal is to have this done via a batch file using task scheduler every night.

I have tried using a couple of different scripts pre written, but would not exclude these prefixed png files, only remove all. How would I go about this?

3 Answers 3

1

Can you try powershell? Something like:

$path = "C:\site\temp"
gci -Path $path | ? {!($_.Name -ilike "abc-*.png")} | % { Remove-Item -Path $_.FullName }
2
  • How would I tell this to apply to the specific folder only (there are no sub folders in there) if I was to say store this in C:\Scripts, but the folder needing action taken was C:\site\temp\ ? Commented Oct 12, 2015 at 3:20
  • I added the $path at the top so you can run the script from any folder. Commented Oct 12, 2015 at 3:23
0

With Batch you could do it in this way:

@Echo OFF 

For %%# In ("*.*") DO (
    If /I "%%~x#" EQU ".png" (
        (Echo "%%~n#"| Findstr "^abc-")1>nul 2>&1 || (
            Del /Q "%%~#"
        )
    )
)


Pause&Exit

I iterate all files (which have an extension), then If file has ".png" extension, I evaluate whether the filename starts with "abc-" to exclude it.

Please do a backup of your folder before testing.

0

Also, please back up the contents of the folder you are working on before testing.

Step One: Make a sub directory underneath the folder in question.
Step Two: Move the files to save into that sub directory.
Step Three: Delete everything remaining in the folder.
Step Four: Move the files from the sub directory back into the folder.
Step Five: Delete the sub directory.
Step Six: See what you have.

A simple script follows.

REM C:\SCRIPTS\MOVERPNG.CMD
C:
ECHO OFF
CLS
CD \SITE\TEMP 
MD BAR  
MOVE /y ABC-*.PNG \SITE\TEMP\BAR  
DEL /y *.PNG  
DEL /y *.CSV  
CD BAR  
MOVE *.PNG C:\SITE\TEMP 
CD ..  
RD /q BAR
ECHO MOVERPNG has completed.
DIR *.* /P /O:N 

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .