Windows cmd удалить все файлы в папке

I use Windows.

I want to delete all files and folders in a folder by system call.

I may call like that:

>rd /s /q c:\destination
>md c:\destination

Do you know an easier way?

rene's user avatar

rene

41.6k78 gold badges114 silver badges152 bronze badges

asked Oct 1, 2009 at 9:32

ufukgun's user avatar

2

No, I don’t know one.

If you want to retain the original directory for some reason (ACLs, &c.), and instead really want to empty it, then you can do the following:

del /q destination\*
for /d %x in (destination\*) do @rd /s /q "%x"

This first removes all files from the directory, and then recursively removes all nested directories, but overall keeping the top-level directory as it is (except for its contents).

Note that within a batch file you need to double the % within the for loop:

del /q destination\*
for /d %%x in (destination\*) do @rd /s /q "%%x"

answered Oct 1, 2009 at 9:41

Joey's user avatar

JoeyJoey

345k85 gold badges690 silver badges687 bronze badges

12

del c:\destination\*.* /s /q worked for me. I hope that works for you as well.

ra.'s user avatar

ra.

1,79814 silver badges15 bronze badges

answered Oct 11, 2012 at 19:45

Sean's user avatar

SeanSean

4634 silver badges2 bronze badges

5

I think the easiest way to do it is:

rmdir /s /q "C:\FolderToDelete\"

The last «» in the path is the important part.

This deletes the folder itself. To retain, add mkdir "C:\FolderToDelete\" to your script.

AlainD's user avatar

AlainD

5,4956 gold badges46 silver badges100 bronze badges

answered Nov 20, 2014 at 10:26

Banan's user avatar

BananBanan

4334 silver badges2 bronze badges

5

Yes! Use Powershell:

powershell -Command "Remove-Item 'c:\destination\*' -Recurse -Force"

answered Feb 16, 2017 at 15:00

Rosberg Linhares's user avatar

Rosberg LinharesRosberg Linhares

3,5471 gold badge32 silver badges35 bronze badges

0

If the subfolder names may contain spaces you need to surround them in escaped quotes. The following example shows this for commands used in a batch file.

set targetdir=c:\example
del /q %targetdir%\*
for /d %%x in (%targetdir%\*) do @rd /s /q ^"%%x^"

answered Jan 24, 2014 at 10:05

fractor's user avatar

fractorfractor

1,5342 gold badges15 silver badges30 bronze badges

To delete file:

del PATH_TO_FILE

To delete folder with all files in it:

rmdir /s /q PATH_TO_FOLDER

To delete all files from specific folder (not deleting folder itself) is a little bit complicated. del /s *.* cannot delete folders, but removes files from all subfolder. So two commands are needed:

del /q PATH_TO_FOLDER\*.*
for /d %i in (PATH_TO_FOLDER\*.*) do @rmdir /s /q "%i"

You can create a script to delete whatever you want (folder or file) like this mydel.bat:

@echo off
setlocal enableextensions

if "%~1"=="" (
    echo Usage: %0 path
    exit /b 1
)

:: check whether it is folder or file
set ISDIR=0
set ATTR=%~a1
set DIRATTR=%ATTR:~0,1%
if /i "%DIRATTR%"=="d" set ISDIR=1

:: Delete folder or file
if %ISDIR%==1 (rmdir /s /q "%~1") else (del "%~1")
exit /b %ERRORLEVEL%

Few example of usage:

mydel.bat "path\to\folder with spaces"
mydel.bat path\to\file_or_folder

answered Nov 10, 2016 at 17:44

Maxim Suslov's user avatar

Maxim SuslovMaxim Suslov

4,4051 gold badge36 silver badges29 bronze badges

One easy one-line option is to create an empty directory somewhere on your file system, and then use ROBOCOPY (http://technet.microsoft.com/en-us/library/cc733145.aspx) with the /MIR switch to remove all files and subfolders. By default, robocopy does not copy security, so the ACLs in your root folder should remain intact.

Also probably want to set a value for the retry switch, /r, because the default number of retries is 1 million.

robocopy "C:\DoNotDelete_UsedByScripts\EmptyFolder" "c:\temp\MyDirectoryToEmpty" /MIR /r:3

answered May 27, 2014 at 15:43

BateTech's user avatar

BateTechBateTech

5,8383 gold badges20 silver badges31 bronze badges

I had an index folder with 33 folders that needed all the files and subfolders removed in them. I opened a command line in the index folder and then used these commands:

for /d in (*) do rd /s /q "%a" & (
md "%a")

I separated them into two lines (hit enter after first line, and when asked for more add second line) because if entered on a single line this may not work. This command will erase each directory and then create a new one which is empty, thus removing all files and subflolders in the original directory.

SteveTurczyn's user avatar

SteveTurczyn

36.1k6 gold badges41 silver badges53 bronze badges

answered Jul 8, 2014 at 19:43

Ynotinc's user avatar

0

Community's user avatar

answered Jun 20, 2016 at 17:41

NoWar's user avatar

NoWarNoWar

36.5k81 gold badges325 silver badges500 bronze badges

1

It takes 2 simple steps. [/q means quiet, /f means forced, /s means subdir]

  1. Empty out the directory to remove

    del *.* /f/s/q  
    
  2. Remove the directory

    cd ..
    rmdir dir_name /q/s
    

See picture

answered May 11, 2020 at 21:51

Jenna Leaf's user avatar

Jenna LeafJenna Leaf

2,29521 silver badges29 bronze badges

1

try this, this will search all MyFolder under root dir and delete all folders named MyFolder

for /d /r "C:\Users\test" %%a in (MyFolder\) do if exist "%%a" rmdir /s /q "%%a"

Paul Roub's user avatar

Paul Roub

36.3k27 gold badges84 silver badges93 bronze badges

answered Jul 14, 2020 at 17:57

Shailesh Tiwari's user avatar

del .\*

This Command delete all files & folders from current navigation in your command line.

answered Nov 14, 2020 at 9:11

Yuvraj Hinger's user avatar

I would like to delete all files and subfolders in a batch file in Windows 7 and keep the top folder. Basically emptying the folder. What’s the command line instruction for that?

djsmiley2kStaysInside's user avatar

asked Aug 9, 2010 at 16:42

Tony_Henrich's user avatar

Tony_HenrichTony_Henrich

11.6k29 gold badges86 silver badges116 bronze badges

3

You can do this using del and the /S flag (to tell it to remove all files from all subdirectories):

del /S C:\Path\to\directory\*

Breakthrough's user avatar

Breakthrough

34.3k10 gold badges105 silver badges149 bronze badges

answered Aug 9, 2010 at 16:46

MDMarra's user avatar

13

The best Solution:
e.g. i want to delete all files and sub-directories of parent directory lets say «C:\Users\Desktop\New folder\». The easy way is create batch file of below three commands.

cd C:\Users\Desktop\New folder\

del * /S /Q

rmdir /S /Q «C:\Users\Desktop\New folder\»

Here first it will clean all files in all sub-directories and then cleans all empty sub-directories.
Since current working directory is parent directory i.e.»\New folder», rmdir command can’t delete this directory itself.

BlueBerry - Vignesh4303's user avatar

answered Oct 5, 2013 at 4:44

Annasaheb's user avatar

AnnasahebAnnasaheb

3793 silver badges2 bronze badges

6

Navigate to the parent directory:

pushd "Parent Directory"

Delete the sub folders:

rd /s /q . 2>nul

Hashim Aziz's user avatar

Hashim Aziz

12.1k35 gold badges99 silver badges167 bronze badges

answered Jul 3, 2014 at 12:38

user340956's user avatar

user340956user340956

2292 silver badges2 bronze badges

6

rmdir "c:\pathofyourdirectory" /q /s

Don’t forget to use the quotes and for the /q /s it will delete all the repositories and without prompting.

Excellll's user avatar

Excellll

12.6k11 gold badges51 silver badges78 bronze badges

answered Jul 31, 2013 at 18:23

SuperUser's user avatar

SuperUserSuperUser

951 silver badge1 bronze badge

2

You can do it quickly and easily by putting these three instructions in your bat file:

mkdir empty_folder
robocopy /mir empty_folder "path_to_directory"
rmdir empty_folder

answered Feb 2, 2017 at 19:20

fireblood's user avatar

firebloodfireblood

3452 gold badges5 silver badges14 bronze badges

2

user340956 was painfully close to the solution, but you know what they say about close…

To be clear, rd /s /q c:\foobar deletes the target directory in addition to its contents, but you don’t always want to delete the directory itself, sometimes you just want to delete its contents and leave the directory alone. The deltree command could do this, but Micrsoft, in its infinite «wisdom» removed the command and didn’t port it to Windows.

Here’s a solution that works without resorting to third-party tools. It’s probably about as simple and efficient as is possible with a command-line script instead of outright writing an actual executable. It doesn’t set any environment variables and it doesn’t use any loops. It’s also as safe as can be, with error-checking everywhere possible, and also as user-friendly as possible, with built-in docs.

dt.bat (or dt.cmd for the kids; whatever, I’m old, I use .bat 🤷):

:: dt is a Windows-compatible version of the deltree command
:: Posted to SuperUser by Synetech: https://superuser.com/a/1526232/3279

@echo off
goto start

:start
    if ["%~1"]==[""] goto usage
    pushd "%~1" 2>nul
    if /i not ["%cd%"]==["%~1"] goto wrongdir
    rd /s /q "%~1" 2>nul
    popd
goto :eof

:usage
    echo   Delete all of the contents of a directory
    echo.
    echo   ^> %0 DIR
    echo.
    echo   %0 is a substitute for deltree, it recursively deletes the contents
    echo   (files and folders) of a directory, but not the directory itself
    echo.
    echo   DIR is the directory whose contents are to be deleted
goto :eof

:wrongdir
    echo Could not change to the target directory. Invalid directory? Access denied?
goto :eof

Here’s how it works:

  1. It checks if a command-line argument has been passed, and prints usage information and quits if not.
  2. It uses pushd to save the current directory, then switch to the target directory, redirecting any errors to nul for a cleaner command-line experience (and cleaner logs).
  3. It checks to see if the current directory is now the same as the target directory, and prints an error message and quits if it is not. This avoids accidentally deleting the contents of the previous directory if the pushd command failed (e.g., passing an invalid directory, access-error, etc.)
    • This check is case-insensitive, so it’s usually safe on Windows, but isn’t for any case-sensitive file-systems like those used by *nix systems, even under Windows.
    • It doesn’t work with short-filenames (e.g. C:\Users\Bob Bobson\foobar won’t be seen as being the same as C:\Users\BobBob~1\foobar even if they actually are). It’s a slight inconvenience to have to use the non-short filename, but it’s better safe than sorry, especially since SFNs aren’t completely reliable or always predictable (and may even be disabled altogether).
  4. It then uses rd to delete the target directory and all of its contents, redirecting any errors (which there should be at least one for the directory itself) to nul. Some notes about this:
    • Because the target directory is the current directory, the system has an open file-handle to it, and thus it cannot actually delete it, so it remains as is, which is the desired behavior.
    • Because it doesn’t try to remove the target directory until after its contents have been removed, it should now be empty (other than anything that also has open file handles).
  5. Finally, it uses popd to return to the previously-current directory and ends the script.

(If you like, you can comment the script with the above descriptions using rem or ::.)

answered Feb 17, 2020 at 22:41

Synetech's user avatar

SynetechSynetech

68.3k36 gold badges223 silver badges357 bronze badges

2

you can use rmdir to delete the files and subfolder, like this:

rmdir /s/q MyFolderPath

However, it is significantly faster, especially when you have a lot of subfolders in your structure to use del before the rmdir, like this:

del /f/s/q MyFolderPath > nul
rmdir /s/q MyFolderPath

answered Apr 27, 2015 at 7:21

Einbert Alshtein's user avatar

2

1. What the OP asked for

del /f /s /q "C:\some\Path\*.*"
rmdir /s /q "C:\some\Path"
mkdir "C:\some\Path"

That will remove all files and folders in and including the directory of "C:\some\Path" but remakes the top directory at the end.

2. What most people will want

del /f /s /q "C:\some\Path\*.*"
rmdir /s /q "C:\some\Path"

That will completely remove "C:\some\Path" and all of its contents

If OP has some oddly specific requirement to not touch the top-level directory in any capacity… they should mention that in their question :)

answered Jan 22, 2021 at 8:03

kayleeFrye_onDeck's user avatar

1

If you want to delete all files in a folder, including all subfolders and not rely on some error conditions to keep the root folder intact (like I saw in another answer)
you could have a batch file like this:

@echo off

REM Checking for command line parameter
if "%~1"=="" (

    echo Parameter required.
    exit /b 1

) else (

    REM Change directory and keep track of the previous one
    pushd "%~1"

    if errorlevel 1 (

        REM The directory passed from command line is not valid, stop here.
        exit /b %errorlevel%

    ) else (

        REM First we delete all files, including the ones in the subdirs, without confirmation
        del * /S /Q

        REM Then we delete all the empty subdirs that were left behind
        for /f %%D IN ('dir /b /s /a:d "%~1"') DO rmdir /S /Q "%%D"

        REM Change directory back to the previous one
        popd

        REM All good.
        exit /b 0
    )

)

And then you would simply call it with:

empty_my_folder.bat "C:\whatever\is\my folder"

answered Feb 5, 2014 at 16:39

Gio's user avatar

1

To delete file:

del PATH_TO_FILE

To delete folder with all files in it:

rmdir /s /q PATH_TO_FOLDER

To delete all files from specific folder (not deleting folder itself) is a little bit complicated. del /s *.* cannot delete folders, but removes files from all subfolder. So two commands are needed:

del /q PATH_TO_FOLDER\*.*
for /d %i in (PATH_TO_FOLDER\*.*) do @rmdir /s /q "%i"

You can create a script to delete whatever you want (folder or file) like this mydel.bat:

@echo off
setlocal enableextensions

if "%~1"=="" (
    echo Usage: %0 path
    exit /b 1
)

:: check whether it is folder or file
set ISDIR=0
set ATTR=%~a1
set DIRATTR=%ATTR:~0,1%
if /i "%DIRATTR%"=="d" set ISDIR=1

:: Delete folder or file
if %ISDIR%==1 (rmdir /s /q "%~1") else (del "%~1")
exit /b %ERRORLEVEL%

Few example of usage:

mydel.bat "path\to\folder with spaces"
mydel.bat path\to\file_or_folder

answered Nov 10, 2016 at 17:16

Maxim Suslov's user avatar

To delete all subdirectories and their contents use robocopy. Create an empty directory, for example C:\Empty. Let’s say you want to empty C:\test which has lots of subdirectories and files and more subdirectories and more files:
robocopy c:\empty c:\test /purge
then, rd C:\test if need be.

answered May 18, 2021 at 9:31

David Walker's user avatar

This worked better for me when I had spaces in the folder names.

@echo off
REM ---- Batch file to clean out a folder
REM Checking for command line parameter
if "%~1"=="" (

echo Parameter required.
exit /b 1

) else (
echo ***********************************************************************************
    echo *** Deleting all files, including the ones in the subdirs, without confirmation *** 
    del "%~1\*" /S /Q
echo ***********************************************************************************
    REM Deleting all the empty subdirs that were left behind
FOR /R "%~1" %%D IN (.) DO (
    if "%%D"=="%~1\."  (
    echo *** Cleaning out folder: %~1 *** 
    ) else (
    echo Removed folder "%%D"
    rmdir /S /Q "%%D"
    )
) 

    REM All good.
    exit /b 0

)

answered Feb 13, 2014 at 18:06

Ed Hammond's user avatar

1

If you wanted to empty the folder, my take is:

@ECHO OFF

:choice
cls
set /P c=Which directory? [Desktop, Documents, Downloads, Pictures]
if /I "%c%" EQU "Desktop" set Point = "Desktop"
if /I "%c%" EQU "Documents" set Point = "Documents"
if /I "%c%" EQU "Downloads" set Point = "Downloads"
if /I "%c%" EQU "Pictures" set Point = "Pictures"
if /I "%c%" EQU "Videos" set Point = "Videos"
goto choice
set /P d=Which subdirectory? If you are putting multiple. Your's should be like "path/to/folder" (no files!!)


IF NOT EXIST C:\Users\%USERNAME%\%Point%\%d% GOTO NOWINDIR
rmdir C:\Users\%USERNAME%\%Point%\%d%
mkdir C:\Users\%USERNAME%\%Point%\%d%
:NOWINDIR
mkdir C:\Users\%USERNAME%\%Point%\%d%

Simple as that!
I hope I helped you out!
I recommend you to take the whole code, if you don’t want to take the whole code, then you can simplify this with.

IF NOT EXIST *path here* GOTO NOWINDIR
rmdir *path here*
mkdir *path here*
:NOWINDIR
mkdir *path here*

EDIT:
rmdir won’t work if it isn’t empty. To fix that.

IF NOT EXIST *path here* GOTO NOWINDIR
del *path here*/* /S /Q (dont copy this, the above prevents the del command from deleting everything in the folder, this is simallar to another answer.)
rmdir *path here*
mkdir *path here*
:NOWINDIR
mkdir *path here*

Not sure if this works but…

sdelete -s -p *path here*/*

answered Jul 30, 2020 at 8:56

ThisIsACoolBoy's user avatar

None of the answers already posted here is very good, so I will add my own answer.

Try this:

for /f "delims=" %i in ('dir path\to\folder /s /b /a:-d') do del "%i" /f /q /s
fot /f "delims=" %i in ('dir path\to\folder /s /b /a:d') do rd "%i" /q /s

This should do it.

answered Jan 22, 2021 at 14:28

Ξένη Γήινος's user avatar

Ξένη ΓήινοςΞένη Γήινος

2,8846 gold badges29 silver badges63 bronze badges

1

Seems everyone is missing the fact that we’re wanting to delete multiple sub folders, but NOT delete the parent folder. We may also no know all the names of the subfolders, and don’t want to do each one individually.

So, thinking outside the box, this is how I solved this issue.

mkdir c:\EmptyFolderToBeDeletedSoon

Robocopy /Purge c:\EmptyFolderToBeDeletedSoon c:\FolderIWantEmpty

rmdir c:\EmptyFolderToBeDeletedSoon

Make a temp directory that’s empty.
Use the RoboCopy command with the /Purge switch (/PURGE :: delete dest files/dirs that no longer exist in source.) using the empty folder as the source, and the folder we want empty as the destination.
Delete the empty temp folder we created to be the empty source for Robocopy.

Now, you have an empty folder of all files and folders, which is what this whole string was about.

answered Aug 15, 2022 at 20:07

Vokard's user avatar

This is what worked for me.

  1. Navigate inside the folder where you want to delete the files.
  2. Type: del *
  3. Y for yes.
  4. Done

Glorfindel's user avatar

Glorfindel

4,0998 gold badges24 silver badges37 bronze badges

answered May 7, 2018 at 18:43

Erv's user avatar

Example: Delete everything (folders/subfolders/files) in 3D Objects folder but want to leave 3D Objects folder alone

pathThere=»C:\Users\PhilosophyPoet\3D Objects»
CD pathThere
RMDIR /s /q pathThere

When CMD is oriented to working directory, using RMDIR will delete all folders, subfolders and files from the working directory. Seems like CMD process cannot process itself just like ‘I can’t throw myself into rubbish bin because the rubbish bin need to be seal by someone’

answered Oct 1, 2020 at 13:36

Mashimaro's user avatar

Here’s a two-line solution I just came up with, possibly exploiting a bug or unexpected behavior in robocopy. This works with the newest version of cmd and robocopy on Windows 10 at this writing.

It mirror syncs an empty sub-folder to its parent folder. In other words, it tells the parent folder to have all the same files as the sub-folder: none. Amusingly, this means it also deletes the empty sub-folder that it is instructed to sync with.

This example will empty the Temp folder for the current user. Note that it is using the %TEMP% environment variable, which cmd expands to whatever that may be, for example C:\Users\Dobby_the_Free\AppData\Local\Temp:

mkdir %TEMP%\i_like_cheez
robocopy /mir %TEMP%\i_like_cheez %TEMP%

answered Jan 30, 2021 at 1:44

r_alex_hall's user avatar

r_alex_hallr_alex_hall

3263 silver badges12 bronze badges

this script works with folders with a space in the name

for /f «tokens=*» %%i in (‘dir /b /s /a:d «%~1″‘) do rd /S /Q «%%~i»

answered Feb 20, 2021 at 22:40

rubafix's user avatar

You must log in to answer this question.

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

.

Some folders and files are impossible to delete using Windows Explorer. These include files with long paths, names or reserved names like CON, AUX, COM1, COM2, COM3, COM4, LPT1, LPT2, LPT3, PRN, NUL etc. You will get an Access Denied error message when you try to delete these files using Windows Explorer, even if you are an administrator.

Regardless of the reason, these can only be force deleted using command line only. This article explains using cmd to delete folder or file successfully.

Table of contents

  • Before we begin
  • How to remove files and folders using Command Prompt
    • Del/Erase command in cmd
    • Rmdir /rd command in cmd
    • Delete multiple files and folders
    • Delete files and folders in any directory
    • Check the existence of file or folder then remove using IF command
  • How to remove files and folders using Windows PowerShell
    • Delete multiple files and folders
    • Delete files and folders in any directory
  • Delete files and folders with complex and long paths using the command line
  • Closing words

Before we begin

Here are some important things for you to understand before we dig into removing files and folders using Command Prompt and Windows PowerShell. These tips will help you understand the terms and some basic rules of the commands that will be used further in the article.

The most important thing to remember here is the syntax of the path and file/folder name. When typing file name, notice whether there is a gap (space) in it. For example, if the folder name has no space in it, it can be written as-is. However, if there is a gap in it, it will need to be written within parenthesis (“”). Here is an example:

CLI naming syntax

Another thing to remember is that you might see different outcomes while removing folders that are already empty, and folders that have some content in them. Having said that, you will need to use the dedicated options in the command to remove content from within a folder along with the main folder itself. This is called a recursive action.

Furthermore, you must also know how to change your working directory when inside a Command Line Interface. Use the command cd to change your directory, followed by the correct syntax. Here are some examples:

One last thing that might come in handy is being able to view what content is available in the current working directory. This is especially helpful so that you type in the correct spelling of the target file or folder. To view the contents of the current working directory in Command Prompt and PowerShell, type in Dir.

dir

Now that we have the basic knowledge, let us show you how you can delete files and folders using the command line on a Windows PC.

By default, there are 2 command-line interfaces built into Windows 10 – Command Prompt and Windows PowerShell. Both of these are going to be used‌ ‌to‌ ‌delete‌ ‌content‌ ‌from‌ ‌a‌ ‌computer.

How to remove files and folders using Command Prompt

Let us start with the very basic commands and work our way up from there for Command Prompt. We recommend that you use Command Prompt with administrative privileges so that you do not encounter any additional prompts that you already might have.

Del/Erase command in cmd

Del and Erase commands in Command Prompt are aliases of one another. Meaning, both perform the same function regardless of which one you use. These can be used to remove individual items (files) in the current working directory. Remember that it cannot be used to delete the directories (folders) themselves.

Use either of the following commands to do so:

Tip: Use the Tab button to automatically complete paths and file/folder names.

Del File/FolderName

Erase File/FolderName

Replace File/FolderName with the name of the item you wish to remove. Here is an example of us removing files from the working directory:

del erase cmd

If you try to remove items from within a folder, whether empty or not, you will be prompted for a confirmation action, such as the one below:

confirmation yes no

In such a scenario, you will need to enter Y for yes and N for no to confirm. If you select yes, the items directly within the folder will be removed, but the directory (folder) will remain. However, the subdirectories within the folder will not be changed at all.

This problem can be resolved by using the /s switch. In order to remove all of the content within the folder and its subdirectories, you will need to add the recursive option in the command (/s). The slash followed by “s” signifies the recursive option. Refer to the example below to fully understand the concept:

We will be using the Del command here to recursively remove the text files within the folder “Final folder,” which also has a subdirectory named “Subfolder.” Subfolder also has 2 sample text files that we will be recursively removing with the following command:

Del /s "Final folder"

Here is its output:

recursive del

As you can see in the image above, we had to enter “y” twice – once for each folder. with each confirmation, 2 text files were removed, as we had stated earlier in this example. However, if we use File Explorer, we can still see that both the directories – “Final folder” and “Subfolder” – are still there, but the content inside them is removed.

You can also make another tweak to the command so that it is executed silently and you will not be prompted for confirmation. Here is how:

Del /s /q "Final folder"

The /q illustrates that the action be taken quietly.

quiet del

Rmdir /rd command in cmd

Similar to Del and Erase, rmdir and rd are also aliases for one another, which means to remove directory. These commands are used to remove the entire directory and subdirectories (recursively) including their contents. Use the command below to do so:

rmdir "New Folder"

rmdir cmd

The above command will remove the “New folder” only if it is empty. If a folder has subdirectories, you might get the following prompt:

directory is not empty

In this case, we will need to apply the option for recursive deletion of items as we have done earlier with the Del command.

rmdir /s "Final folder"

rmdir recursive

Of course, this can also be performed with the /q option so that you are not prompted with a confirmation.

rmdir /s /q "Final folder"

rmdir recursive quiet

Delete multiple files and folders

Up until now, we have completed the task of deleting single items per command. Now let’s see how you can remove multiple selective files or folders. Use the command below to do so:

For files:

Del "File1.txt" "File3.txt" "File5.txt"

del multiple files

For directories:

rd "Folder1" "Folder3" "Folder5"

rd multiple folders

Here is a before and after comparison of the directory where both of the above commands were executed:

before vs after

You can also use an asterisk (*) concatenated with a file type or file name to perform bulk removal of files with the Del command. However, Microsoft has removed the support for the use of asterisks with rmdir so that users do not accidentally remove entire folders.

Here is an example of us removing all .txt files from our current working directory:

Del "*.txt"

del asterisk

Delete files and folders in any directory

We are working on removing content within the current working directory. However, you can also use the commands we have discussed till now to remove files and folders from any directory within your computer.

Simply put the complete path of the item you want to delete in enclosed parenthesis, and it shall be removed, as in the example below:

different directory rmdir

Check the existence of file or folder then remove using IF command

We have already discussed that you can view the contents of the working directory by typing in Dir in Command Prompt. However, you can apply an “if” condition in Command Prompt to remove an item if it exists. If it will not, the action would not be taken. Here is how:

if exist File/FolderName (rmdir /s/q File/FolderName)

Replace File/FolderName in both places with the name of the item (and extension if applicable) to be deleted. Here is an example:
if exist Desktop (rmdir /s/q Desktop)

cmd if

How to remove files and folders using Windows PowerShell

The commands in Windows PowerShell to delete and remove content from your PC are very much similar to those of Command Prompt, with a few additional aliases. The overall functionality and logic are the same.

We recommend that you launch Windows PowerShell with administrative privileges before proceeding.

The main thing to note here is that unlike Command Prompt, all commands can be used for both purposes – removing individual files as well as complete directories. We ask you to be careful while using PowerShell to delete files and folders, as the directory itself is also removed.

The good thing is that you do not need to specify recursive action. If a directory has sub-directories, PowerShell will confirm whether you wish to continue with your deletion, which will also include all child objects (subdirectories).

Here is a list of all the commands/aliases that can be used in PowerShell to remove an item:

  • Del
  • Rm-dir
  • remove-item
  • Erase
  • Rd
  • Ri
  • Rm

We tested all of these commands in our working directory and each of them was successful in deleting the folders as well as individual items, as can be seen below:

PS all

As can be seen above, the syntax of all the aliases is the same. You can use any of the commands below to delete an item using PowerShell:

Del File/FolderName
Rm-dir File/FolderName
remove-item File/FolderName
Erase File/FolderName
Rd File/FolderName
Ri File/FolderName
Rm File/FolderName

Delete multiple files and folders

You can also delete multiple selective files and folders just as we did while using Command Prompt. The only difference is that you will need to provide the complete path of each item, even if you are in the same working directory. Use the command below to do so:

Del "DriveLetter:\Path\ItemName", "DriveLetter:\Path\ItemName"

Remember to append the file type if the item is not a directory (.txt, .png, etc.), as we have done in the example below:

PS delete selective 1

You can also use an asterisk (*) concatenated with a file type or file name to perform bulk removal of files with the Del command, as done in Command Prompt. Here is an example:

PS asterisk

The command shown above will remove all.txt files in the directory “New folder.”

Delete files and folders in any directory

You can also remove an item in a different directory, just like we did in Command Prompt. Simply enter the complete path to the item in PowerShell, as we have done below:

PS different location

Delete files and folders with complex and long paths using the command line

Sometimes you may encounter an error while trying to delete an item that may suggest that the path is too long, or the item cannot be deleted as it is buried too deep. Here is a neat trick you can apply using both Command Prompt and PowerShell to initially empty the folder, and then remove it using any of the methods above.

Use the command below to copy the contents of one folder (which is empty) into a folder that cannot be deleted. This will also make the destination folder empty, hence making it removable.

robocopy "D:\EmptyFolder" D:\FolderToRemove /MIR

In this scenario, the EmptyFolder is the source folder that we have deliberately kept empty to copy it to the target folder “FolderToRemove.”

robocopy

You will now see that the folder that was previously unremovable is now empty. You can proceed to delete it using any of the methods discussed in this article.

Closing words

The command line is a blessing for Windows users. You can use any of these commands to remove even the most stubborn files and folders on your computer.

Let us know which solution worked for you in the comments section down below.

Достаточно типовая задача, по удалению всех файлов и содержащихся папок внутри директории без удаления её самой вызывает определенные трудности.
Файлы могут быть скрыты, помечены только для чтения, может содержать системные файлы.

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

RMDIR /S /Q C:\Путь-до-директории
MKDIR C:\Путь-до-директории

Ключь /S — удаление указанного каталога и всех содержащихся в нем файлов и подкаталогов.
Ключь /Q — Отключение запроса подтверждения при удалении.

Альтернативный рабочий вариант, это переход в указанную папку и указание на нее же при удалении

CD "Путь-до-директории"
RMDIR . /S /Q

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

Более сложный вариант, требует гораздо больше количества кода с учетом особенностей, например FOR игнорирует директории со скрытыми атрибутами, поэтому итоговый вариант пакетного BAT файла будет следующим:

@ECHO OFF

SET THEDIR=название-директории-в-которой-происходит-удаление

Echo Удаляем все файлы в %THEDIR%
DEL "%THEDIR%\*" /F /Q /A

Echo Удаляем все директории в %THEDIR%
FOR /F "eol=| delims=" %%I in ('dir "%THEDIR%\*" /AD /B 2^>nul') do RMDIR /Q /S "%THEDIR%\%%I"
@ECHO Удаление завершено.

EXIT

Ключи в DEL обозначают следующее: /A — удалить системные и скрытые, /F — принудительное удаление файлов доступных только для чтения, /Q — не задавать вопросы.
Название директории заключается в коде в двойные кавычки потому, что оно может содержать пробел или один из символов &()[]{}^=;!’+,`~ , если этого не сделать, то пакетный файл отработает с ошибками.

on August 5, 2015

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!

del filename

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

del *

To delete all the files with ‘log’ extension

del *.log

Delete all files having the prefix ‘abc’

del abc*

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

del *PIC*

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

del filename1 filename2 filename3 filename4....

Example:

D:\>dir /s /b
1.pdf 2.pdf 3.pdf
D:\>del 1.pdf 2.pdf 3.pdf
D:\>
D:\>dir /s /b
D:\>

Delete Read only files

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

c:\>attrib readonlyfile.txt
A    R       C:\readonlyfile.txt
c:\>del readonlyfile.txt
c:\readonlyfile.txt Access is denied.
c:\>

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

del /F readonlyfile.txt

Alternatively, we can use the below command too

del /A:R readonlyfile.txt

  • Windows by den официальный сайт
  • Windows cmd if not exist
  • Windows chess game download windows 7
  • Windows cmd права на файл
  • Windows caps lock switch language