Jump to content

Delete current directory content


Recommended Posts

Hi All ,

I want to create a batch file , which do the following

1. first get the current working directory

2. delete all the contents(files, directories ,sub directories) of the current working directory

by the way i have tested the following code but it does not work for me

D:\test>for / d% i in (s *.*) DO del% i / Q / S
/ was unexpected at this time.

D:\test>for / d% i in (s *.*) DO rd% i
/ was unexpected at this time.

D:\test>

Could you plz help me ?

BTW I am using XP , and I want to apply the batch to XP , Vista , Win 7

Link to comment
Share on other sites


Thanks for your reply

You are going to have to explain where the batch file is going to be located, how it is going to be invoked and probably what you mean by current working directory!

Let us assume that we have placed the .batch file at the location "D:\test\mybatch.bat"

once you have browsed to the directory "test" , double clicking on the batch file "mybatch.bat" , it should delete all the contents of the directory "test" ("D:\test")

off course the batch file should delete all the contents of "test" directory except itself "mybatch.bat"

Link to comment
Share on other sites

Let us assume that we have placed the .batch file at the location "D:\test\mybatch.bat"

once you have browsed to the directory "test" , double clicking on the batch file "mybatch.bat" , it should delete all the contents of the directory "test" ("D:\test")

off course the batch file should delete all the contents of "test" directory except itself "mybatch.bat"

This should do:

@echo off
SETLOCAL ENABLEEXTENSIONS
for /f "Tokens=*" %%A in ('dir /B /S /A:-D^|FIND /V "%~nx0"') do ECHO del /q "%%A"
for /f "Tokens=*" %%A in ('dir /B /S /A:D') do ECHO rd /s /q "%%A"

jaclaz

Link to comment
Share on other sites

Thanks jaclaz for your reply ,

@echo off

SETLOCAL ENABLEEXTENSIONS

for /f "Tokens=*" %%A in ('dir /B /S /A:-D^|FIND /V "%~nx0"') do ECHO del /q "%%A"

for /f "Tokens=*" %%A in ('dir /B /S /A:D') do ECHO rd /s /q "%%A"

1. I have copied the above code into empty batch file, saved it , double clicked on it ( batch file) , but nothing happened ( nothing got deleted)

2. I tried to copy , paste the above code into DOS prompt but it displayed error and got hang as the following

D:\test>@echo off
SETLOCAL ENABLEEXTENSIONS
for /f "Tokens=*" %%A in ('dir /B /S /A:-D^|FIND /V "%~nx0"') do ECHO del /q "%%
A"
%%A was unexpected at this time.
for /f "Tokens=*" %%A in ('dir /B /S /A:D') do ECHO rd /s /q "%%A"
%%A was unexpected at this time.

Link to comment
Share on other sites

1: Of course the batch supplied has echo before the del command.

2: And when you copied the commands to a dos prompt, it also normal as the syntax used by Jaclaz shouldn't be used there.

Edited by allen2
Link to comment
Share on other sites

Here is the VBS way of doing what you want, it will delete all sub folders

and files in the parent directory and leave this script

Save As Delete_Contents.vbs


Dim Fso :Set Fso = CreateObject("Scripting.FileSystemObject")
Dim Col, Obj, Str
'-> Loop To Get Script Name Only
For Each Obj In Split(WScript.ScriptFullName,"\")
Str = Obj
Next
'-> Loop To Delete Files In Current Directory
For Each Col In Fso.GetFolder(".").Files
'-> Filter So You Dont Delete This File
If Not LCase(Col.Path) = LCase(WScript.ScriptFullName) Then
Fso.DeleteFile Col.Path, True
End If
Next
'-> Function To Loop Threw Parent Folder
'-> And All Sub Folders
Recursive(Fso.GetFolder("."))
Function Recursive(Folder)
On Error Resume Next
For Each Obj In Folder.SubFolders
If Not LCase(Obj.Path) = LCase(Replace(WScript.ScriptFullName,Str,"")) Then
Fso.DeleteFolder Obj
End If
Recursive(Obj)
Next
End Function

Change Delete_Contents.vbs.txt to Delete_Contents.vbs to make active.

Delete_Contents.vbs.txt

Link to comment
Share on other sites

Yet another thing that's so much easier in powershell (removing everything in a directory, including subfolders):

dir | del -r

That's all of it. Or you can even use:

ls|rm -r

8 chars total :lol:

Of course, that has to be ran from the proper folder (using cd or adding the path after dir or whatever you like).

With every passing day it feels like vbscript is becoming more of a dead end (where batch files were a decade ago)... So much code for so little work (not that it ever was what one would call a "nice" language). Yes, it's far more powerful than batch, but it's come to a point where even many programming languages make scripting easier and faster than that scripting language (god forbid if you actually have to do something simple, like sorting something)... It's kinda sad really (thankfully powershell often saves the day). Even in C# creating a specialized console app just for this task (let's call it, EmptyFolder.exe or such) is less code:


using System.IO;
class EmptyFolder
{
static void Main(string[] args)
{
DirectoryInfo di = new DirectoryInfo(args[0]);
foreach (FileInfo file in di.GetFiles()) file.Delete();
foreach (DirectoryInfo subdir in di.GetDirectories()) subdir.Delete(true);
}
}

One should add a guard clause in case the specified path doesn't exist though, and perhaps an error message (usage) if no param or more than one is passed (definitely not what I'd call "finished" yet). Or even easier:


using System.IO;
class EmptyFolder
{
static void Main(string[] args)
{
DirectoryInfo di = new DirectoryInfo(args[0]);
di.Delete(true);
di.Create();
}
}

Although the recursion method tends to work better in some scenarios, like when you have files that cannot be deleted.

Link to comment
Share on other sites

Thanks allen2 for your reply,

1: Of course the batch supplied has echo before the del command.

forget about echo command , the problem is that : NOTHING will be deleted after executing the batch file ?????????

You didn't understood at all : The echo command is preventing the del and the rd commands from executing (Jaclaz made it on purpose).

I removed those for you in the following batch:

@echo off
SETLOCAL ENABLEEXTENSIONS
for /f "Tokens=*" %%A in ('dir /B /S /A:-D^|FIND /V "%~nx0"') do del /q "%%A"
for /f "Tokens=*" %%A in ('dir /B /S /A:D') do rd /s /q "%%A"

Edited by allen2
Link to comment
Share on other sites

You didn't understood at all : The echo command is preventing the del and the rd commands from executing (Jaclaz made it on purpose).

Not only he doesn't understand, he also starts shouting! :w00t::ph34r:

OBVIOUSLY, since it is potentially VERY dangerous code, I added a basic safeguard to avoid that some demented users would copy and paste it "as is" in the WRONG place (and delete everything in the subtree by mistake.

The idea was to NOT allow someone that cannot even read two lines of batch to potentially make damages.

Since OP asked help in writing a batch file and posted a non-working code that not only doesn't work but is is also evidently NOT following very basic batch or command line syntax, I assumed he was not at all familiar and thought that a safeguard would have been needed.

jaclaz

Link to comment
Share on other sites

Thanks to who replied,

Especial Thanks to jaclaz (many more thanks) , allen2 && I apologize to all for my rough reply,

@echo off

SETLOCAL ENABLEEXTENSIONS

for /f "Tokens=*" %%A in ('dir /B /S /A:-D^|FIND /V "%~nx0"') do ECHO del /q "%%A"

for /f "Tokens=*" %%A in ('dir /B /S /A:D') do ECHO rd /s /q "%%A"

It works like a charm ........... Again my thanks to jaclaz,allen2

Not only he doesn't understand, he also starts shouting! :w00t::ph34r:

OBVIOUSLY, since it is potentially VERY dangerous code, I added a basic safeguard to avoid that some demented users would copy and paste it "as is" in the WRONG place (and delete everything in the subtree by mistake.

The idea was to NOT allow someone that cannot even read two lines of batch to potentially make damages.

Since OP asked help in writing a batch file and posted a non-working code that not only doesn't work but is is also evidently NOT following very basic batch or command line syntax, I assumed he was not at all familiar and thought that a safeguard would have been needed.

I totally agree with you , I dont know even low level basics of batch script and i did not put any effort to learn it.....It was my mistake

I am sure that your above reply encouraged me alot to start learning batch script and also to spend time trying to understanding the things and trying to solve the problems before post a question.

Link to comment
Share on other sites

Now that you are happy with the result of the supplied script, I'd just like to inform you that in line three alone there are two unnecessary switches and a potentially ineffective method used for the exception. Line four is not much better either!

Link to comment
Share on other sites

This is how you would code in Vb.net 2008 for deleting the contents without deleting the application.

DelContentsImg.png


Public Class Form1
Dim Cd = My.Computer.FileSystem.CurrentDirectory
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
For Each i In My.Computer.FileSystem.GetFiles(Cd)
If InStr(1, i, "DelContents.exe", 1) Then
' This Make Sure The DelContents.exe Is Not Deleted
Else
My.Computer.FileSystem.DeleteFile(i.ToString)
End If
Next
For Each f In My.Computer.FileSystem.GetDirectories(Cd)
My.Computer.FileSystem.DeleteDirectory(f, _
FileIO.UIOption.OnlyErrorDialogs, _
FileIO.RecycleOption.DeletePermanently)
Next
End Sub
End Class

Source Code

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...