Windows command delete all files

Delete files from command line

Deleting files is one of the frequently done operation from Windows command prompt. This post explains how to use ‘del’ command from CMD for different use cases like deleting a single file, deleting files in bulk using wild cards etc. Before we start to look at the syntax, note that the command works only for files and can’t handle folders.

How to delete a file

Run del command with the name of the file to be deleted, you are done!

You do not see message after running the command if the file is deleted successfully. Error message is shown only when something goes wrong.

Delete files in bulk

Del command recognizes wildcard(*) and so can be used to delete files in bulk from CMD. Some examples below.
To delete all the files in current folder

To delete all the files with ‘log’ extension

Delete all files having the prefix ‘abc’

Delete all files having ‘PIC’ somewhere in the file name.

The above are the basic use cases of del command. Continue to read below for non trivial use cases.

Delete multiple files

‘Del’ command can accept multiple files as argument

Delete Read only files

We can’t delete a read-only file using simple‘del’ command. We get access denied error in this scenario.

A read-only file can be deleted by adding /F flag.

Alternatively, we can use the below command too

Is there any batch command to delete all zero byte sized files from cmd.

There is a way to remove folders from the commandline, use “RD” (remove directory), and it has a couple of silent switches, “RD /S /Q C:/Directory” will remove C:/Directory silently, I use this all the time. I think that the directory path has to be in quotations if it contains any spaces.

UAC might want to fight over deleting files, in that case, the command “takeown” to give you ownership of the file first, should get around that.

Sometimes we get an error when we try to delete a File or a folder for no reason , but of course there is a reason.We have many damage file or blocked files.Do not worry if we want to remove the error files or too long path files from our system,here I suggest a smooth way.So use “Long path tool” software and keep yourself.

Well done, I used this when del *1*.*

Will keep this in my reference book. Thanks a lot!

Is there a way to exclude filenames matching a pattern from a delete? For example, I want to delete all files except those whose names are like *xyz*

I am trying to delete csv files in DOS that have a date suffix of earlier
than 2 months ago. I need to do this dynamically, from a batch file.
Is this possible ? Many thanks.
Bethany

I want to delete a file from all the user’s profiles using cmd.
The file is on the desktop.

Name of the file-Hello My Name

I’m writing del %PUBLIC%\Desktop\Hello*My*Name.pdf,but that doesnt seem to work.
I also tried del %PUBLIC%\Desktop\*Hello* but that didnt work too.

Any help is appreciated

c. Using the for loop create 5 text files which start from letter a (ex: a1, a2, a3, a4, a5).

can you help me
create 5 files like this command.
for /l %a in (1 1 5) do mkdir File%a.

Rmdir : Delete directory from command line

Do you want to delete a directory from Windows command prompt(CMD)? This post explains how to use the command rmdir to delete folders and their contents. You can also find examples for each use case of folder deletion – empty folders, non empty folders, folders with white spaced names etc.

Delete folder from CMD

Run the command rmdir on the folder.

Читайте также:  После смены озу не запускается windows

How to delete a non empty folder

The simple rmdir does not work for folders having some content.

Use /s option to delete the folder contents along with the folder. This deletes all subfolders recursively.

Force delete a folder without confirmation

To force delete directory, without being asked for confirmation, we can use /Q switch.

We can also use ‘rd’ in place of ‘rmdir‘. Both names refer to the same command. This command works on Windows 2000, Windows XP, Server 2003, Vista, Windows 7 and 10.

Deleting directory with white spaces in the name

Rmdir can delete files with whitespaces in the name, you just need to wrap up the folder name in double quotes as shown in the below example.

Delete contents of a directory but keep the directory

The usecase here is to delete all the contents of the directory but keep the parent directory so that we do not need to create it again. rmdir /Q /S does not work here as it deletes the parent directory too. Rather the below commands should do the trick.

This works in 2 steps – the first command deletes all files, whereas the second one deletes all subdirectories.

Errors

To delete a directory, you should have appropriate access permissions on the directory. Otherwise rmdir throws ‘Access denied’ error.

Thanks dude..I was looking for command line way of deleting nonempty folders.. cheers.

Good old DOS….something tells me one day the world will be saved by a DOS operation. ; )

cannot delete… access is denied. am trying to delete a directory on a flash drive. cannot access permissions because explorer isn’t working. using win7

Note:
Don’t forget to leave a “space” in the command line..
rmdir /Q /S_“folder with spaces in the name” I meant “space”, ait’t “underscore”. And upper case of “S”. Good luck!

Hi
can you show me an example of command to delete this path in bat file.
C:\Program Files\Microsoft Office Communicator

am not able to do this . some error s

Is this in Windows 7/Vista?.
If so then you need to take ownership of the files. You can do that with below command from elevated administrator command prompt.
takeown /F «c:\Program Files\Microsoft Office Communicator» /R /A

then run the below command to delete this folder.

rmdir /S «c:\Program Files\Microsoft Office Communicator»

cd program files\microsoft office communicator
then enter press
rd /s “filename”
Then enter

I am getting the following error “The process cannot access the file because it is being us
ed by another process.” what should be the case now?

You should not have the Dir you want to delete open… Close it and then try the command again

Could you kindly post the command for deleting my folder which is at Drive G. Name of the folder is Recycler. Thanks

Thank you so much. I was trying to delete an entire directory of files, about 200k folders and files, and it kept throwing a warning “this folder is shared with other people”. No such warning with this command!

i followed your instructions but i’m getting error to delete a folder in cmd. ERROR = The system cannot find the the specified…

You should make “C:” your default Directory, tot do this type “cd.. && cd..” The type the command again but leave the “C:\” and just type the rest of the code.
It should look like this: C:>rmdir /Q /S Users\Owner\Songs\New

i have installed new win 8 n a back up of old win 8 is in c drive with a name windows old n its not being deleted by ANY means . i have tried this one as well but it says on all files access is denied

I tried the process many times but it says “access is denied”….
My entire path is “C:\program files\alwil software\avast5” . How should i delete this avast5 folder with all the folders inside it.

run cmd.exe as administrator
make sure avast service is not running

Every time I try it says the file cant be found

you’re really awesome. Googled a 1000 times just for this line

“C:\>rmdir /S nonemptydir
nonemptydir, Are you sure (Y/N)? y”

Читайте также:  Workcentre 3025 драйвер mac os catalina

Thank you so much for your help. This changed my life.

Thank you so much for your help. This changed my life.
please attache more basic command for beginner person for my email
tnx

I need to do that, help me out

D:\abc\ has files and folders in it

but by using rd or rmdir

rmdir d:\abc\ /s /q will delete abc folder also but i don’t want this.

the asterisk stands for ‘anything’ in or below the named directory.

I want to delete subfolders of a folder older than 10 days.I am able to delete files but not folder

I wanted to know the bat file programm for deleting the contents (sub folders) of a folder on certain conditions. can anyone help.?

How to delete folders created programatically with timestamp attached at the end.

Like we do for files :
DEL comp*

Is there any command for folders:
RM com*
or
RMDIR com*

I’m wanting to delete the directory c:\windows.old I followed the instructions above I run CMD as admin, I typed in: takeown /F c:\windows.old /R /A And hit enter key. It did this part properly but Then I typed in: rmdir /Q /S c:\windows.old And after every entry it said Access denied. what is the command line/s i need to type to atlas delete the directory c:\windows.old ? (using windows 10)

I got the same problem…….
please someone help.

thank you .
i m so glad

I followed the instructions above I run CMD as admin, I typed in: takeown /F c:\windows.old /R /A And hit enter key. It did this part properly but Then I typed in: rmdir /Q /S c:\windows.old And after every entry it said Access denied. what is the command line/s i need to type to atlas delete the directory c:\windows.old ? (using windows 10.
Please somebody help………………………

takeown /f D:\OrganizationalUnit\Everyone /r /d y
icacls D:\OrganizationalUnit\Everyone /grant administrators:F /T
attrib -s -h -r D:\OrganizationalUnit\EVERYONE /s /d
forfiles /P D:\OrganizationalUnit\Everyone\ -S -M *.* /D -2 /C “cmd /c del /f /q @PATH”
forfiles /P D:\OrganizationalUnit\Everyone\ /M * /D -2 /C “cmd /c if @isdir==TRUE rmdir /S /Q @file”

Thank you very much! With these commands I could remove all “c:\Windows.old” files and directories.

Hello,
I have four folders and I want to keep two of them along with their contents and delete other two folders. How can I do that?
My Parent folder -> Folder 1 (file1.txt), Folder 2 (file2.txt), Folder 3 (file3.txt), Folder 4 (file4.txt).
Need to delete or remove 2 folders and keep 2 folder with their content.
Need command for this.
Any help will be appreciated.

Super Cool!! Deleted a stubborn non empty directory in no time. Thanks for this guide.

I have several folder: folder1, folder2, folder3
how to delete all “folder” with *

Note: This commands doest’n work:
RM folder*
or
RMDIR folder*

I want to thank you very much for the help on deleting these files. I ended up using the CMD method, but it worked perfectly. Again, thank you.

Thanks. After struggling for months and hunting the web, I was finally able to delete a folder using your advice “Deleting directory with white spaces in the name”

OMG! Thank you! Was trying to delete the remaining empty folders of an old eset nod, but couldn’t. This did the trick (hoping). I’m just wondering if its still in the background somewhere. T.hanks again

in programatically if any changes in the inner files or directory after delete the parent directory doesnot work
eg:
system(“rmdir /s/q \””d:/test/hari\””);——>it works
but after
system(“rmdir /s/q \””d:/test\””);—–>it doesn’t work

Thank you for these still useful tips.

That worked verywell. Thank You

I tried the command, but someone has created the directory repeatedly and now I can not removed the base directory. Help

E:\>rmdir /s /q thur2
thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Th
ur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur
2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\
Thur2\AC_FSQ

1.ZIP – The file name is too long.
thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Th
ur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur
2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\
Thur2\AC_HR1

1.ZIP – The file name is too long.
thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Th
ur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur
2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\
Thur2\AC_HR1

2.ZIP – The file name is too long.
The path thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2
\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\T
hur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thur2\Thu
r2\Thur2\Thur2\Thur2\AC_FSQ

Как удалить файл или папку через командную строку Windows

Командная строка – мощный инструмент для автоматизации и упрощения многих задач, которые возникают при администрировании компьютера с операционной системой Windows. В этой статье мы рассмотрим команды DEL, ERASE, RD и RMDIR. С их помощью вы сможете удалять файлы и папки прямо из командной строки.

Читайте также:  Windows server sku что такое

Удаление файлов через командную строку

Если вам нужно удалить файл через командную строку, то для этого нужно использовать команду DEL или ERASE . Эти команды являются синонимами и работают одинаково. Вы можете получить подробную информацию об этих командах, если введете их в командную строку с параметром « /? ». Например, вы можете ввести « del /? » и в консоль выведется вся основная информация о команде del .

Команда DEL (или ERASE ) предназначена для удаления одного или нескольких файлов и может принимать следующие параметры:

  • /P – удаление с запросом подтверждения для каждого файла;
  • /F – удаление файлов с атрибутом «только для чтения»;
  • /S – удаление указанного файла из всех вложенных папок;
  • /Q – удаление без запроса на подтверждение ;
  • S — Системные;
  • H — Скрытые;
  • R – Только для чтения;
  • A — Для архивирования
  • Также перед атрибутами можно использовать знак минус «-», который имеет значение «НЕ». Например, «-S» означает не системный файл.

Обычно, для того чтобы воспользоваться командной DEL нужно сначала перейти в папку, в которой находится файл для удаления, и после этого выполнить команду. Для того чтобы сменить диск нужно просто ввести букву диска и двоеточие. А для перемещения по папкам нужно использовать команду « CD ».

После того как вы попали в нужную папку можно приступать к удалению файлов. Для этого просто введите команду DEL и название файла.

Также, при необходимости вы можете удалять файлы, не перемещаясь по папкам. В этом случае нужно указывать полный путь к документу.

Если есть необходимость выполнить запрос на подтверждение удаления каждого их файлов, то к команде DEL нужно добавить параметр « /p ». В этом случае в командной строке будет появляться запрос на удаление файла и пользователю нужно будет ввести букву «Y» для подтверждения.

Нужно отметить, что при использовании параметра «/a», отвечающие за атрибуты буквы нужно вводить через двоеточие. Например, для того чтобы удалить все файлы с атрибутом «только для чтения» и с расширением «txt» нужно ввести команду « del /F /A:R *.txt ».

Аналогичным образом к команде DEL можно добавлять и другие параметры. Комбинируя их вы сможете создавать очень мощные команды для удаления файлов через командную строку Windows. Ниже мы приводим еще несколько примеров:

  • del D:\ — уничтожение всех файлов в корне диска D;
  • del D:\*.txt – уничтожение всех файлов с расширением txt в корне диска D;
  • del D:\doc – уничтожение всех файлов в папке d:\doc (документы с атрибутами будут пропущены);
  • del /A:r d:\doc\*.txt – уничтожение всех файлов с атрибутом «только для чтения» и расширением «txt» в папке d:\doc;

Удаление папок через командную строку

Если вам нужно удалить папку через командную строку Windows, то указанные выше команды вам не помогут. Для удаления папок существует отдельная команда RD или RMDIR (сокращение от английского Remove Directory).

Команды RD и RMDIR являются синонимами и предназначены для удаления папок. Они могу принимать следующие параметры:

  • /S — удаление всего дерева каталогов, при использовании данного параметра будет удалена не только сама папка, но и все ее содержимое;
  • /Q – удаление дерева папок без запроса на подтверждение;

Например, для того чтобы удалить папку достаточно ввести команду RD и название папки.

Если папка содержит вложенные папки или файлы, то при ее удалении будет выведена ошибка».

Для решения этой проблемы к команде RD нужно добавить параметр « /s ». В этом случае удаление проходит без проблем, но появляется запрос на подтверждение удаления.

Для того чтобы удаление дерева папок прошло без появления запроса на подтверждение к команде нужно добавить параметр « /q ». В этом случае папка удаляется без лишних вопросов.

Также команда RD может принимать сразу несколько папок, для этого их нужно просто разделить пробелом. Например, если выполнить « rd 111 222 », то за один раз можно удалить папки с названиями « 111 » и « 222 ».

Если же вам нужно удалить через командную строку папку, которая сама содержит пробел, то в этом случае ее название нужно взять в двойные кавычки.

Комбинируя команды DEL и RD , можно создавать мощные скрипты для очистки и удаления папок в операционной системе Windows.

Оцените статью