Delete user directory windows

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.

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

Читайте также:  Что делать если при запуске windows комп зависает

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”

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

Читайте также:  Все для windows angels

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

Directory. Delete Метод

Определение

Удаляет заданный каталог и при необходимости все подкаталоги. Deletes a specified directory, and optionally any subdirectories.

Перегрузки

Удаляет пустой каталог по заданному пути. Deletes an empty directory from a specified path.

Удаляет заданный каталог и, при наличии соответствующей инструкции, все подкаталоги и файлы в нем. Deletes the specified directory and, if indicated, any subdirectories and files in the directory.

Delete(String)

Удаляет пустой каталог по заданному пути. Deletes an empty directory from a specified path.

Параметры

Имя пустого каталога, который необходимо удалить. The name of the empty directory to remove. Этот каталог должен поддерживать запись и быть пустым. This directory must be writable and empty.

Исключения

Файл с тем же именем и расположении, заданном path , уже существует. A file with the same name and location specified by path exists.

-или- -or- Каталог является текущим рабочим каталогом приложения. The directory is the application’s current working directory.

-или- -or- Каталог, заданный параметром path , не пустой. The directory specified by path is not empty.

-или- -or- Каталог доступен только для чтения или содержит файл, доступный только для чтения. The directory is read-only or contains a read-only file.

-или- -or- Каталог используется другим процессом. The directory is being used by another process.

У вызывающего объекта отсутствует необходимое разрешение. The caller does not have the required permission.

path представляет собой строку нулевой длины, содержащую только пробелы или один или несколько недопустимых символов. path is a zero-length string, contains only white space, or contains one or more invalid characters. Вы можете запросить недопустимые символы с помощью метода GetInvalidPathChars(). You can query for invalid characters by using the GetInvalidPathChars() method.

path имеет значение null . path is null .

Указанный путь, имя файла или оба значения превышают максимальную длину, заданную в системе. The specified path, file name, or both exceed the system-defined maximum length.

Параметр path не существует или не найден. path does not exist or could not be found.

-или- -or- Указан недопустимый путь (например, он ведет на несопоставленный диск). The specified path is invalid (for example, it is on an unmapped drive).

Примеры

В следующем примере показано, как создать новый каталог и подкаталог, а затем удалить только подкаталог. The following example shows how to create a new directory and subdirectory, and then delete only the subdirectory.

Комментарии

Этот метод ведет себя так же, как и аргумент, Delete(String, Boolean) false указанный для второго параметра. This method behaves identically to Delete(String, Boolean) with false specified for the second parameter.

path Параметр может указывать сведения относительного или абсолютного пути. The path parameter may specify relative or absolute path information. Сведения об относительном пути интерпретируется как относительно текущего рабочего каталога. Relative path information is interpreted as relative to the current working directory. Сведения о получении текущего рабочего каталога см. в разделе GetCurrentDirectory . To obtain the current working directory, see GetCurrentDirectory.

Конечные пробелы удаляются из конца path параметра перед удалением каталога. Trailing spaces are removed from the end of the path parameter before deleting the directory.

Этот метод создает исключение, IOException Если каталог, указанный в path параметре, содержит файлы или подкаталоги. This method throws an IOException if the directory specified in the path parameter contains files or subdirectories.

path Параметр не учитывает регистр. The path parameter is not case-sensitive.

В некоторых случаях, если указанный каталог открыт в проводнике, Delete метод может не иметь возможности его удалить. In some cases, if you have the specified directory open in File Explorer, the Delete method may not be able to delete it.

Применяется к

Delete(String, Boolean)

Удаляет заданный каталог и, при наличии соответствующей инструкции, все подкаталоги и файлы в нем. Deletes the specified directory and, if indicated, any subdirectories and files in the directory.

Читайте также:  Журнал системных ошибок windows

Параметры

Имя каталога, который необходимо удалить. The name of the directory to remove.

Значение true позволяет удалить каталоги, подкаталоги и файлы по заданному path , в противном случае — значение false . true to remove directories, subdirectories, and files in path ; otherwise, false .

Исключения

Файл с тем же именем и расположении, заданном path , уже существует. A file with the same name and location specified by path exists.

-или- -or- Каталог, заданный параметром path , доступен только для чтения, или recursive имеет значение false и path не является пустым каталогом. The directory specified by path is read-only, or recursive is false and path is not an empty directory.

-или- -or- Каталог является текущим рабочим каталогом приложения. The directory is the application’s current working directory.

-или- -or- Каталог содержит файл только для чтения. The directory contains a read-only file.

-или- -or- Каталог используется другим процессом. The directory is being used by another process.

У вызывающего объекта отсутствует необходимое разрешение. The caller does not have the required permission.

path представляет собой строку нулевой длины, содержащую только пробелы или один или несколько недопустимых символов. path is a zero-length string, contains only white space, or contains one or more invalid characters. Вы можете запросить недопустимые символы с помощью метода GetInvalidPathChars(). You can query for invalid characters by using the GetInvalidPathChars() method.

path имеет значение null . path is null .

Указанный путь, имя файла или оба значения превышают максимальную длину, заданную в системе. The specified path, file name, or both exceed the system-defined maximum length.

Параметр path не существует или не найден. path does not exist or could not be found.

-или- -or- Указан недопустимый путь (например, он ведет на несопоставленный диск). The specified path is invalid (for example, it is on an unmapped drive).

Примеры

В следующем примере показано, как создать новый каталог, подкаталог и файл в подкаталоге, а затем рекурсивно удалить все новые элементы. The following example shows how to create a new directory, subdirectory, and file in the subdirectory, and then recursively delete all the new items.

Комментарии

path Параметр может указывать сведения относительного или абсолютного пути. The path parameter may specify relative or absolute path information. Сведения об относительном пути интерпретируется как относительно текущего рабочего каталога. Relative path information is interpreted as relative to the current working directory. Сведения о получении текущего рабочего каталога см. в разделе GetCurrentDirectory . To obtain the current working directory, see GetCurrentDirectory.

Конечные пробелы удаляются из конца path параметра перед удалением каталога. Trailing spaces are removed from the end of the path parameter before deleting the directory.

path Параметр не учитывает регистр. The path parameter is not case-sensitive.

Если recursive параметр имеет значение true , пользователь должен иметь разрешение на запись для текущего каталога, а также для всех подкаталогов. If the recursive parameter is true , the user must have write permission for the current directory as well as for all subdirectories.

Поведение этого метода немного отличается при удалении каталога, содержащего точку повторного анализа, например символическую ссылку или точку подключения. The behavior of this method differs slightly when deleting a directory that contains a reparse point, such as a symbolic link or a mount point. Если точка повторного анализа является каталогом, например точкой подключения, она отключается и точка подключения удаляется. If the reparse point is a directory, such as a mount point, it is unmounted and the mount point is deleted. Этот метод не выполняет рекурсивный перебор точки повторного анализа. This method does not recurse through the reparse point. Если точка повторного анализа является символьной ссылкой на файл, то точка повторного анализа удаляется, а не целевой объект символьной ссылки. If the reparse point is a symbolic link to a file, the reparse point is deleted and not the target of the symbolic link.

В некоторых случаях, если указанный каталог открыт в проводнике, Delete метод может не иметь возможности его удалить. In some cases, if you have the specified directory open in File Explorer, the Delete method may not be able to delete it.

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