Link to home
Start Free TrialLog in
Avatar of Frans_Truyens
Frans_TruyensFlag for Belgium

asked on

vbs script to delete first file in a directory

I am looking for a vbs script in a directory. I just want to delete the first one, not all of them. Also I don't know its name.
Avatar of Michele Segato
Michele Segato
Flag of Italy image

What do you mean by first file?
First created file?
First name?
Random one of them?
Is this code the one you are looking for?
Dim fso, folder, files, sFolder, flf
  
  Set fso = CreateObject("Scripting.FileSystemObject")
  sFolder = "c:\tmp"
  Set folder = fso.GetFolder(sFolder)
  Set files = folder.Files
  
  For each flf In files
    flf.Delete
  Next

Open in new window

Ops! You told only one file!
Here is tyhe corrected script
Dim fso, folder, files, sFolder, flf
  
  Set fso = CreateObject("Scripting.FileSystemObject")
  sFolder = "c:\tmp"
  Set folder = fso.GetFolder(sFolder)
  Set files = folder.Files
  
  For each flf In files
    flf.Delete
    exit for
  Next

Open in new window

Avatar of oBdA
oBdA

Well, what constitutes "first one"? In alphabetical order, by date, by size, by name length, by extension, ...?
Some examples for batch (.cmd) files (all in test mode, remove the ECHO to run them for real):

To delete the newest file in the current folder:
for /f "delims=" %%a in ('dir /a:-d /o:d /b') do set DeleteFile=%%a
ECHO del "%DeleteFile%"

Open in new window


To delete the oldest file:
for /f "delims=" %%a in ('dir /a:-d /o:-d /b') do set DeleteFile=%%a
ECHO del "%DeleteFile%"

Open in new window


To delete the alphabetically first file:
f
or /f "delims=" %%a in ('dir /a:-d /o:-n /b') do set DeleteFile=%%a
ECHO del "%DeleteFile%"

Open in new window


And the alphabetically last file:
for /f "delims=" %%a in ('dir /a:-d /o:n /b') do set DeleteFile=%%a
ECHO del "%DeleteFile%"

Open in new window

Avatar of Frans_Truyens

ASKER

I don't want to delete them all. I just want to delete the first one in the list. The date is not important, the size is not important. I just want to delete the first one.
With my second post you can delete only a file.
But again. First by name or what?
That looks better. How do I delete the newest one? With VBS please
ASKER CERTIFIED SOLUTION
Avatar of Michele Segato
Michele Segato
Flag of Italy image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks a lot. This solved my problem