Subfolders in a given folder via the command prompt?

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

28 gold badges85 silver badges115 bronze badges

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

10 gold badges104 silver badges149 bronze badges

answered Aug 9, 2010 at 16:46

MDMarra's user avatar

del * /S /Q

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

3 silver badges2 bronze badges

Navigate to the parent directory:

pushd "Parent Directory"

Delete the sub folders:

rd /s /q . 2>nul

Hashim Aziz's user avatar

31 gold badges93 silver badges157 bronze badges

answered Jul 3, 2014 at 12:38

user340956's user avatar

2 silver badges2 bronze badges

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

11 gold badges51 silver badges78 bronze badges

answered Jul 31, 2013 at 18:23

SuperUser's user avatar

1 silver badge1 bronze badge

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

2 gold badges5 silver badges13 bronze badges

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

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.

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

36 gold badges222 silver badges356 bronze badges

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

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

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*

sdelete -s -p *path here*/*

answered Jul 30, 2020 at 8:56

ThisIsACoolBoy's user avatar

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.

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

answered Jan 22, 2021 at 8:03

kayleeFrye_onDeck's user avatar

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

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

Ξένη Γήινος

6 gold badges25 silver badges60 bronze badges

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.

Robocopy /Purge c:\EmptyFolderToBeDeletedSoon c:\FolderIWantEmpty

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

8 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

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.

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

3 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

I want to remove all files from a folder structure, so I’m left with an empty folder structure.

Can this be achieved in either batch or VBScript scripting?

What can you suggest?

Peter Mortensen's user avatar

asked Apr 15, 2014 at 12:40

RobN's user avatar

This can be accomplished using PowerShell:

Get-ChildItem -Path C:\Temp -Include *.* -File -Recurse | foreach { $_.Delete()}

This command gets each child item in $path, executes the delete method on each one, and is quite fast. The folder structure is left intact.

If you may have files without an extension, use

Get-ChildItem -Path C:\Temp -Include * -File -Recurse | foreach { $_.Delete()}

It appears the -File parameter may have been added after PowerShell v2. If that’s the case, then

Get-ChildItem -Path C:\Temp -Include *.* -Recurse | foreach { $_.Delete()}

It should do the trick for files that have an extension.

:/>  Как исправить ошибку 0xc004f074 в Windows 10

If it does not work, check if you have an up-to-date version of Powershell

Community's user avatar

answered Apr 15, 2014 at 13:18

MDMoore313's user avatar

1 gold badge27 silver badges31 bronze badges

Short and sweet PowerShell. Not sure what the lowest version of PS it will work with.

Remove-Item c:\Tmp\* -Recurse -Force

tobassist's user avatar

answered Nov 2, 2017 at 17:21

Evan Nadeau's user avatar

Evan Nadeau

1 gold badge7 silver badges2 bronze badges

You can do so with del command:

dir C:\folder
del /S *

The /S switch is to delete only files recursively.

answered Apr 15, 2014 at 12:44

ek9's user avatar

3 gold badges20 silver badges20 bronze badges

Get-ChildItem -Path c:\temp -Include * | remove-Item -recurse 

bwDraco's user avatar

43 gold badges164 silver badges204 bronze badges

answered Oct 28, 2014 at 15:39

Gregory Suvalian's user avatar

Reading between the lines on your original question I can offer an alternative BATCH code line you can use. What this will do when ran is only delete files that are over 60 days old. This way you can put this in a scheduled task and when it runs it deletes the excess files that you don’t need rather than blowing away the whole directory. You can change 60 to 5 days or even 1 day if you wanted to. This does not delete folders.

forfiles -p "c:\path\to\files" -d -60 -c "cmd /c del /f /q @path"

answered Apr 15, 2014 at 13:18

Travis's user avatar

8 silver badges16 bronze badges

Use PowerShell to Delete a Single File or Folder. Before executing the Delete command in powershell we need to make sure you are logged in to the server or PC with an account that has full access to the objects you want to delete.

With Example: http://dotnet-helpers.com/powershell-demo/how-to-delete-a-folder-or-file-using-powershell/

Using PowerShell commnads to delete a file

Remove-Item -Path “C:\dotnet-helpers\DummyfiletoDelete.txt”

The above command will execute and delete the “DummyfiletoDelete.txt” file which present inside the “C:\dotnet-helpers” location.

Using PowerShell commnads to delete all files

Remove-Item -Path “C:\dotnet-helpers*.*”

Using PowerShell commnads to delete all files and folders

Remove-Item -Path “C:\dotnet-helpers*.*” -recurse

-recurse drills down and finds lots more files. The –recurse parameter will allow PowerShell to remove any child items without asking for permission. Additionally, the –force parameter can be added to delete hidden or read-only files.

Using -Force command to delete files forcefully

Using PowerShell command to delete all files forcefully

Remove-Item -Path “C:\dotnet-helpers*.*” -Force

Adil H. Raza's user avatar

answered May 10, 2018 at 7:13

thiyagu selvaraj's user avatar

This is the easiest way IMO

Open PowerShell, navigate to the directory (cd), THEN

ls -Recurse * | rm

If you want to delete based on a specific extension

ls -Recurse *.docx | rm

ls is listing the directory

-Recurse is a flag telling powershell to go into any sub directories

* says everything

*.doc everything with .doc extension

All the other answers appear to make this more confusing than necessary.

answered Oct 12, 2016 at 20:45

Kellen Stuart's user avatar

Kellen Stuart

2 gold badges8 silver badges18 bronze badges

Try this using PowerShell. In this example I want to delete all the .class files:

Get-ChildItem '.\FOLDERNAME' -include *.class -recurse | foreach ($_) {remove-item $_.FullName}

Peter Mortensen's user avatar

answered Nov 20, 2014 at 21:28

Bacara's user avatar

2 bronze badges

  1. In Windows Explorer select the root dir containing all the files and folders.

  2. Search for *

  3. Sort by Type (All the folders will be at the top and all the files listed underneath)

  4. Select all the files and press Delete.

This will delete all the files and preserve the directory structure.

answered Mar 16, 2015 at 9:12

Emel's user avatar

Delete all files from current directory and sub-directories but leaving the folders structure.

Caution : try it without the /Q to make sure you are not deleting anything precious.

del /S * /Q 

answered May 18, 2015 at 11:30

hdoghmen's user avatar

We can delete all the files in the folder and its sub folders via the below command.

Get-ChildItem -Recurse -Path 'D:\Powershell Practice' |Where-Object{$_.GetType() -eq [System.IO.FileInfo]} |Remove-Item
Get-ChildItem -Recurse -Path 'D:\Powershell Practice' -File | Remove-Item

answered Mar 1, 2020 at 6:34

Dishant Batra's user avatar

dir C:\testx\ -Recurse -File | rd -WhatIf
What if: Performing the operation "Remove File" on target "C:\testx\x.txt".
What if: Performing the operation "Remove File" on target "C:\testx\bla\x.txt".

bertieb's user avatar

36 gold badges40 silver badges52 bronze badges

answered Apr 10, 2017 at 10:36

With Powershell 5.1:


$extensions_list = Get-ChildItem -Path 'C:\folder_path\' -Recurse
foreach ( $extension in $extensions_list) { if ($extension.Attributes -notlike "Directory") { Remove-Item $extension.FullName }
}

It’s removes all itens that are not Directory.

$extension.FullName = Item Path

$extension.Attributes = Item Type ( Directory or Archive )

answered Feb 4, 2020 at 17:43

Maycon Paixão's user avatar

I found some paths don’t play nicely, so using -LiteralPath works in all cases.

Help on which can be found on the MS docs for Remove-Item.

# To delete all files within a folder and its subfolders.
$subDir = "Z:\a path to\somewhere\"
# Remove the -WhatIf and -Verbose here once you're happy with the result.
Get-ChildItem -LiteralPath $subDir -File -Recurse | Remove-Item -Verbose -WhatIf

answered Jun 11, 2021 at 22:54

Ste's user avatar

1 gold badge9 silver badges22 bronze badges

Remove-Item C:\Test\* -Include *.* -Recurse

Check the official documentation which provides multiples examples.

answered Feb 17, 2022 at 10:53

Nereis's user avatar

2 bronze badges

As a complement to the above answers, actually there’s no need to use the Get-Childitem and pass the result to the pipeline in the above answers, because the -Include keyword is included in the Remove-Item command

One can simply:

Remove-Item -Include “.” “C:\Temp” -Recurse

answered Oct 14, 2018 at 14:59

Sams0nT's user avatar

asked Aug 23, 2010 at 19:29

Eric Wilson's user avatar

Eric Wilson

12 gold badges40 silver badges50 bronze badges

deltree if I remember my DOS.


This removes the directory C:\test, with prompts :

rmdir c:\test /s

This does the same, without prompts :

rmdir c:\test /s /q
runas /user:Administrator cmd
rmdir c:\test /s /q

answered Aug 23, 2010 at 19:30

Colin Pickard's user avatar

Colin Pickard

3 gold badges30 silver badges38 bronze badges

robocopy "D:\new folder" D:\Administrator /MIR

In this case the folder paths were so long they would not even fit in the command prompt window Screen Buffer, but Robocopy will traverse the structure and remove any “extra” files and folders (ie anything not in the new empty folder, which is everything).

answered Aug 9, 2012 at 23:13

Sean's user avatar

5 silver badges3 bronze badges

rm C:\path\to\delete -r -f[orce]

answered Aug 22, 2015 at 16:51

Devesh Khandelwal's user avatar

For me, what works is

del /s dir

You can add /q to disable confirmation. I’ve never managed to get rmdir working (on XP)

answered May 17, 2014 at 7:42

Vincent Fourmond's user avatar

If you have a really really long path, (like I did because of java program error), even robocopy cant do it. It descended for about 30sec into my path and then hung.

My solution: if you can move the whole problem path from one folder to another then you can cut away recursivly and repeatedly some directory stairs from the top.

This Batch plays pingpong between the two directories leer and leer2 and cuts away 8 ‘libraries’
each time. If your path contains files, you have to add further commands to erase them.

recurdel.cmd
:loop
move c:\leer\libraries\libraries\libraries\libraries\libraries\libraries\libraries\libraries c:\leer2
rd /S /Q c:\leer\libraries
move c:\leer2\libraries\libraries\libraries\libraries\libraries\libraries\libraries\libraries c:\leer
rd /S /Q c:\leer2\libraries
GOTO loop

Eric Wilson's user avatar

12 gold badges40 silver badges50 bronze badges

answered Mar 5, 2014 at 8:37

Paulmann's user avatar

1 silver badge1 bronze badge

From CMD Just run RD /s C:\path\to\delete

Hit Y to the prompt

/s ensures all the sub directories are deleted as well.

  • Run help RD from the command line

Wasif's user avatar

2 gold badges15 silver badges32 bronze badges

answered Jan 22, 2016 at 6:44

Rachit Ranjan's user avatar

Remove-Item "Path" -Force -Recurse

In short (nearly rm -rf):

rm "PATH" -r -fo

answered Sep 25, 2020 at 2:10

Wasif's user avatar

2 gold badges15 silver badges32 bronze badges

This will delete “my folder” without prompt:

rd /s /q "C:\Users\gourav.g\AppData\Roaming\my folder"

answered Jul 4, 2018 at 7:09

GorvGoyl's user avatar

1 silver badge12 bronze badges

  • How to delete files on Windows 10 with CMD
  • How to delete folders on Windows 10 with CMD
  • Force Uninstall

Deleting files on Windows 10 with command prompt

The built-in del command can help you delete files on Windows 10. You have to point out the specific path to this file on your PC.

  1. Open the Start Menu and in the search bar type “cmd”. Right-click on the result and select “Run as Administrator”
  2. Type in the field the following command where PATH will be replaced with the full path to the file you want to delete.
    del path
    delete file with command prompt
  3. After that press Enter

Lets’ see this example to clarify the whole process:

After you enter this command the file will be deleted from the Desktop.

There are several commands that you can use to modify a bit the del command.

For instance, you can add the /p parameter to the command to get Command Prompt to be asked for confirmation before deleting a file.

You can also add the /f parameter to force delete a read-only file.

You can also use Revo Uninstallers’ force uninstall feature if you have trouble removing stubborn programs.

To delete folders in Windows 10 with CMD you have to use the rmdir command

This command will remove all folders including the subfolders and files in them.

  1. Open the Start Menu and in the search bar type “cmd”. Right-click on the result and select “Run as Administrator”
  2. Type in the field the following command where PATH will be replaced with the full path to the file you want to delete.
    rmdir PATH
    remove folder with command prompt
  3. Press Enter to finish the process

After you press Enter the folder named “Info” on your desktop will be deleted.

If you want to delete all the files and subfolders in the folder you want to delete, add the /s parameter. This will ensure that the folder is removed including the subfolders and files in it.

Conclusion

As you’ve noticed, commands to delete files and folders in Windows 10 can be pretty handy if you have trouble deleting them the regular way.

Windows Command Prompt Overview

What is Command Prompt? It is a command-line interpreter application also known as cmd.exe or cmd. It can only be used in Windows operating system, and it is a gorgeous tool that can help you do a lot of advanced operations and solve some Windows issues.

Command Prompt is functional, you can deal with USB virus remove with cmd or activate Windows using cmd, and you can use it to delete files and folders very fast with the del command and rmdir command, especially if you have several items to erase. We will teach you how to use cmd delete files with a detailed tutorial.

First, you can check a video to help understand how to use Command Prompt to delete files, and we have listed the essential moments:

  • 00:15 How to open Command Prompt
  • 00:27 Use the del command to delete files
  • 01:56 Use the del command to delete folders

How to Use CMD Delete File Step by Step

First, you need to know that using cmd to delete files is not like putting files and folders into Windows Recycle Bin. You can recover files from Recycle Bin folder directly, but it is not easy to recover cmd deleted files without third-party recovery software. So be careful when you are deleting files with cmd. Make sure you delete the files you don’t want anymore. Now let us learn how to open cmd first.

How to Open Command Prompt on Windows 11/10

We will teach you the easiest way to open the Command Prompt on Windows.

Step 1. Click “Start”, and you’ll see the search box.

Step 2. Type in cmd

how to delete files with cmd

Step 4. Now you can use Command Prompt to delete files.

How to Use  CMD Delete File with del

Step 1. Type in del with a space after it.

Step 2. Then type the path for each file you want to delete, and remember to add spaces to separate each file name.

Step 3. Make sure you type in the right path and press the Enter key.

how to delete files with cmd

How to Use CMD Delete Folders with rmdir

Step 1. Type in rmdir with a space after it.

Step 2. Then type the path for each folder you want to delete.

Step 3. Make sure you type in the right path and press the Enter key.

how to delete folders with cmd

Recover Deleted Files/Folders from CMD with the File Recovery Tool

It is possible that you accidentally delete key files and folders, and you don’t know how to recover permanently deleted files. You can easily return these essential items with EaseUS Data Recovery Wizard.

:/>  Какими клавишами можно заменить пробел на клавиатуре

You don’t have to worry about how to recover deleted videos, photos, music, emails, and documents. EaseUS Data Recovery Wizard can ensure you don’t bother with data loss anymore.

It is also a handy tool, and you can recover deleted files and folders in three steps.

Step 1. Select a location and start scanning

Launch EaseUS Data Recovery Wizard, hover on the partition/drive where the deleted files were stored. Click “Scan” to find lost files.

select a location where you deleted files

Step 2. Select the files you want to recover

When the scanning has finished, select the deleted files you want to recover. You can click on the filter to display only the file types you want. If you remember the file name, you can also search in the “Search files or folders” box, which is the fastest way to find the target file. 

Choose recoverable files

Step 3. Preview and recover deleted files

Preview the recoverable files. Then, select files you want to restore and click “Recover” to store the files at a new storage locations instead of the disk where the data was previously lost.

Recover deleted files

Summary

Except for deleting files with Command Prompt, there are many other things cmd can do on Windows. For example, if you can’t find the file and find it is hidden. It is possible to show hidden files using cmd.

When you are using the computer or laptop, if you want to get back deleted videos, photos, or files, download EaseUS Data Recovery Wizard immediately, and you can find your lost files in one click.

Command Prompt Delete File FAQs

We have listed some further questions and answers here:

What is delete command in cmd?

You will need the del command and rmdir command to delete files and folders with Command Prompt. And the del command is the most common command to erase one or multiple files.

How do I delete corrupted files in cmd?

When you find you can’t commonly delete corrupted files, you can try deleting files with cmd.

  1. 1. Click “Start”, and you’ll see the search box.
  2. 2. Type in cmd.
  3. 3. Right-click cmd and select “Run as Administrator”.
  4. 4. Type the following command Del /F /Q /A, and add the path of corrupted files.
  5. 4. Press the Enter key.

How do I delete multiple files in command prompt?

You can delete a single file and multiple files with the del command.

  1. 1. Type in del with a space after it.
  2. 2. Then type the path for each file you want to delete, and remember to add spaces to separate each file name.
  3. 3. Make sure you type in the right path and press the Enter key.

How delete all files and folders using cmd?

You can use cmd to delete all the files and folders using del and the /S flag ( to tell cmd to remove all files from all subdirectories).

Deleting files or folders in Windows 10 is something we do all the time. Regular file deleting simply requires you to right-click on the item and select the Delete option from the context menu, or after selecting the file, press the Delete key on your keyboard directly.

Force Delete Folder Windows 10 Using Del Command in CMD

Windows’ Command Prompt can be used to perform advanced operations, including forcing delete folders or files, whether or not a program is using them. If you’re a computer expert, Command Prompt is a great disk and file management tool for you.

Here’s how to force delete a folder on Windows 10.

Step 1. Press Win + E to open File Explorer. Find the file or folder that is to be deleted. Copy the location of the file or folder.

copy file location

run cmd as administrator

e.g. del D:\Pictures. Replace the FilePath with the file or folder address copied in Step 1.

use del in cmd to force delete files

Step 4. Type Y for “Are you sure (Y/N)?” and press Enter. Then, the folder will be deleted fast.

Warning
The DEL command will permanently delete a folder or file bypass the Recycle Bin on your Windows PC, and you can’t restore it unless using a professional file recovery tool.

How to Recover Permanently Deleted Folders or Files on Windows 10/11

You may permanently lose files by accidental deletion/formatting, hard drive corruption, virus attack, or OS crash. In any case, you can use EaseUS data recovery software to retrieve lost or deleted files safely and efficiently.

EaseUS Data Recovery Wizard is one of the top-notch data recovery software that you can use to recover lost and deleted files stored on HDD, SSD, SD card, USB flash drive, pen drive, and many more devices without hassle.

What’s more, it’s also good at repairing corrupted files after data recovery. You can repair corrupted videos (MOV/MP4/GIF), photos(JPEG/JPG/BMP/PNG), and documents (DOC/DOCX/XLS/XLSX) effortlessly.

Now, free download this reliable file recovery program to restore more than 1000 kinds of files like video, audio, documents, graphics, emails, and other files.

Step 1. Select the location to scan

Choose the specific device and drive where you have permanently deleted files using Shift delete or emptying recycle bin. Then, click the “Scan” button to find lost files.

select a location and click scan

Step 2. Check the results

The software will automatically start scanning all over the selected drive. When the scan completes, select the “Deleted Files” and “Other Lost Files” folders in the left panel. Then, apply the “Filter” feature or click the “Search files or folders” button to quickly find the deleted files.

scan permanently deleted files

Step 3. Recover deleted files

Select the deleted files and click “Preview”. Next, click “Recover” to save them to another secure location or device.

select files and click recover

Use a File Shredder Tool to Force Delete a Folder or File

Another useful way to remove folders or files that cannot be deleted is using a simple file shredder. EaseUS LockMyFile is an easy-to-use file management tool that can help you delete and shred files or folders from your computer completely with its File Shredder feature.

Step 1. Download and launch EaseUS LockMyFile.

Step 2. Click “File Shredder” under More Tools, click “Add Files, Add Folders, or Add drive” to select files, folders, or a disk that you need to shred.

Step 3. Confirm the files, folder, or drive that you need to shred, click “Safe Delete” or “Disk Wiper” to shred the selected items.

force delete folder software

These are for removing unwanted folders or files. The software is best known for file/folder protection, including file encryption, file locking, file hiding, and so on. If you need maximum protection for your important data, try this tool.

Force Delete Folders Windows 10 by Changing File Ownership

Step 1. Go to Windows File Explorer and find the file/folder you need to delete. Right-click it and select “Properties”.

Take ownership of file or folder.

Step 2. Click “Security” > “Advanced” as shown in the screenshot below.

Fix 'You'll need to provide administrator permission to copy files or folder' error.

Change a user.

Change owner to take a ownership of target files or folders.

Step 4. If you want to change the owner of all sub-containers and objects, tick the “Replace owner on sub-containers and objects” box.

Change subcontainers to fix 'access denied' issue.

Then, try again to see if you can delete folders or files that cannot be deleted.

Gain ownership to force delete folder on Windows 7:

Step 1. Right-click the target folder or file and choose “Properties”.

Step 2. Click the “Security” >”Advanced”. 

take the ownership in windows 7

Step 3. Click the “Owner” > “Edit” to change the owner.

edit the ownership in windows 7

choose other users groups

Force Delete a Folder or File Using Safe Mode

If the above methods failed, you still have the last chance to force delete folders on Windows 10 or Windows 11 in Safe Mode. In safe mode, most applications will not start, so there is a very simple environment to delete a file/folder.

Step 1. Click the Windows button and choose “Power”. Hold the “shift” key and click “Restart”.

how to boot into Safe Mode from start - 2

Step 2. Click the “Troubleshoot” > “Advanced options”.

how to boot into Safe Mode from start - 3

how to boot into Safe Mode from start - click restart

Step 4. From the startup settings, choose one way to enable Safe Mode as listed in numbers 4, 5, and 6.select the Windows 10 Safe Mode according to your needs

Then, your Windows computer will start in Safe Mode. You can try to delete folders or files again. 

Concluding Words and FAQs

We covered these four working solutions to help you force delete a folder or file in Windows 10 or Windows 11. Other quick tips you can try to remove an undeletable folder or folder are checking your antivirus, which protects your files from being deleted, rebooting your system, uninstalling some third-party applications, and more.

Before performing force delete, make sure that the data you are going to clear is the target folder or file. If an error occurs, stop using your computer or external device and use EaseUS data recovery software to retrieve your data immediately.

More Force Delete Folder FAQs

1. How to force delete folder Windows 10 open in another program?

To overcome the File in Use error when deleting folders, you can:

  • Close the program via the Task Manager
  • Restart your computer
  • Force delete folder using CMD
  • Force delete folder with software

2. Force delete folder software

  • EaseUS LockMyFile: its File Shredder feature allows you to completely delete folders, files, or even wipe the whole disk
  • EaseUS Partition Master Free: its Wipe Data feature enables you to clean partition data permanently

3. How to force delete folder Windows 10 PowerShell

Step 2. In the Command Prompt window, type remove-item D:\Pictures and hit Enter key.

Tip: Replace D:\Pictures with the location of the file or folder you need to delete.

Updated by
Cedric on Apr 19, 2023

Fast fix – you can use Shift + Delete to delete files or folders permanently. If you still can’t delete files in Windows 11/10, check the 4 ways in this post on how to force delete a file that cannot be deleted on your Windows 11/10 computer.

Sometimes you might encounter a folder that you’re unable to delete. If you want to fix this problem, you must know the reason first. Generally, the file is used or locked would be the main reason. Otherwise, a virus must be taken into account.

It’s most likely because another program is currently trying to use the file. This can occur even if you don’t see any programs running. When a file is open by another app or process, Windows 11/10 puts the file into a locked state, and you can’t delete, modify, or move it to another location. Usually, after the file is no longer in use, the application will unlock it automatically, but that’s not always the case. Sometimes, a file may not unlock successfully, and even if you try to take any action, you’ll see a warning that the operation can’t be completed because it’s open by another program.

Before you take actions to delete the undeletable files, you can first try these simple tips and delete these files:

  • Close all the programs.
  • Restart your computer.
  • Let the antivirus scan your computer to see if there’s a virus on your computer and get rid of it.

Method 1. Force Delete File that Cannot Be Deleted Using a Third-party Tool

There are many third-party applications that can help you with this problem and delete locked files. One tool that might help you with this problem is EaseUS BitWiper. It can help to clean up junk files and wipe the whole data. It’s fully compatible with Windows 11/10/8/7 etc.

Free download this software and start deleting undeletable files now.

Step 1. Launch EaseUS BitWiper and click “File Shredder”.

Select File Shredder

Step 2. Click “Add Files” to select the files you need to shred, or you can drag files, documents, images, music files, etc., into the center area.

Select files to shred

Step 3. Re-select files that you need to shred and click “Shred” to confirm.

Confirm to shred files

Step 4. The program will immediately shred all the selected files. When it finishes, click “Done”.

Complete shredding files

It’s important to note that unlocking and deleting files on Windows 11/10 may cause system and program issues, depending on the type of files you’re trying to unlock. So be careful of what you delete if you’re not sure of the consequences.

Method 2. How to Delete Files that Cannot be Deleted from Task Manager

Usually, can’t delete file because it is open in system. You could receive the information when you can’t delete a file, like this screenshot, files cannot be deleted if the file is open in an application.

force to delete a file - 1

Step 1. Go to Start, type Task Manager, and choose “Task Manager” to open it.

Step 2. Find the application that is currently using the file, and select “End task”.

Step 3. Then, try to delete the file again on your Windows PC.

force to delete a file -2

Method 3. How to Delete File that Cannot be Deleted with Command Prompt

How to delete a file that won’t delete? Using Command Prompt for deletion is sometimes more efficient, and you definitely should give it a try. Here’s what you need to do to delete a certain file or folder with Command Prompt:

:/>  Для перехода в родительский каталог в командной строке необходимо выполнить

open command prompt

Method 3. Enter Safe Mode to Fix “File Won’t Delete”

Usually, when you come across a locked file, you can simply restart your device to unlock it. If it doesn’t work, you can boot into Safe Mode to unlock and delete the file. 

Step 1. Open “Settings” > Click on “Update & Security” > Click on “Recovery” > Under “Advanced Startup”, click the “Restart now” button.

Step 2. Click on “Troubleshoot” > “Advanced options” > “Startup Settings”.

Step 3. Click the “Restart” button.

Step 4. On “Startup Settings,” press F4 to enable Safe Mode.

click trouble shoot and choose the following settings

While in Safe Mode, use File Explorer to locate and delete the files that were previously locked, then simply restart your device as you would normally to exit Safe Mode.

Tip
Before we delete the undeletable files by wiping the whole partition, you must backup other useful files in advance. Once you start the erasing process, you can’t be canceled it until it is finished. Do remember to check the folders again to avoid data loss.

Video Guide – Fix Can’t Delete File or Folder on Windows 11

Can’t delete file because it is open in system? This tutorial released by Britec09 shows you how to force delete a files and folders using command prompt, powershell and unlock-it. See how to delete a file that is open in system.

  • Use CMD – 1:06
  • Run Powershell – 4:34
  • Unlock software – 5:31

Bonus Tips – How to Recover Deleted Files or Folders

There are times you mistakenly deleted a needed file on your Windows 11, 10, 8.1, 8, 7 computers, we also provide you with additional help. You can recover deleted files with easy-to-use data recovery software. EaseUS Data Recovery Wizard is my recommendation. It is the best file recovery software that allows you to:

  • Restore data from internal and external hard drives, SSD, USB flash drive, SD card, etc.
  • Retrieve lost videos, photos, Word files, music, and more.
  • Repair corrupt/damaged photos, and repair MP4 files.
  • Download and install EaseUS Data Recovery Wizard on your computer and follow the operations below to recover deleted files.

Step 1. Select the location to scan

Choose the specific device and drive where you have permanently deleted files using Shift delete or emptying recycle bin. Then, click the “Scan” button to find lost files.

select a location and click scan

Step 2. Check the results

The software will automatically start scanning all over the selected drive. When the scan completes, select the “Deleted Files” and “Other Lost Files” folders in the left panel. Then, apply the “Filter” feature or click the “Search files or folders” button to quickly find the deleted files.

scan permanently deleted files

Step 3. Recover deleted files

Select the deleted files and click “Preview”. Next, click “Recover” to save them to another secure location or device.

select files and click recover

How to Delete Files that Cannot Be Deleted FAQs

How do you force delete a file that won’t delete?

  • To do this, start by opening the Start menu (Windows key), typing run, and hitting Enter. 
  • In the dialogue that appears, type cmd and hit Enter again. 
  • With the command prompt open, enter del /f filename, where filename is the name of the file or files (you can specify multiple files using commas) you want to delete.

How to force delete folder?

To force delete folder: It is recommended trying Shift + Delete to permanently delete a file or folder. Besides this shortcut, Command Prompt, Safe Mode, and third-party file shredder software can give a back.

Can’t delete a file is open in the system?

To Overcome the “File in Use” Error:

  • Close the Program. Let’s start with the obvious. 
  • Reboot your computer. 
  • End the Application via the Task Manager.
  • Change File Explorer Process Settings. 
  • Disable the File Explorer Preview Pane.
  • Force Delete the File in Use via the Command Prompt.

How do I end a DLL process?

  • Go and find the “Search” button in the “Start” menu. You should search “All files and folders”.
  • Then type the name of that DLL file you want to stop running into the search dialogue box. 
  • Locate the DLL file and write down the full file path for the DLL file.

Can I delete Aow_drv?

No. No matter how much you try but you cannot delete aow_drv. It is a log file and you cannot delete this file.

Conclusion

This post provides you with four effective solutions. Most users say that they have solved their problems after they have tried Method 1. And Method 1 is my first choice. If you have some alternate solution to this problem, and you’d like to share it with us, please tell us, our readers would love to read it.

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

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

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

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

  • – удаление с запросом подтверждения для каждого файла;
  • – удаление файлов с атрибутом «только для чтения»;
  • – удаление указанного файла из всех вложенных папок;
  • – удаление без запроса на подтверждение ;
  • – удаление файлов согласно их атрибутам;

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

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

перемещение по папкам

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

del test.txt

удаление файла

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

del e:\tmp\test.txt

удаление файла по полному адресу

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

del /p test.txt

запрос на подтверждение удаления

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

del /F /A:R *.txt

удаление файлов с атрибутом

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

Уничтожение всех файлов в корне диска D:

del D:\

Уничтожение всех файлов с расширением «» в корне диска :

del D:\*.txt

Уничтожение всех файлов в папке (документы с атрибутами будут пропущены):

del D:\doc

Уничтожение всех файлов с атрибутом «только для чтения» и расширением «» в папке :

del /A:r d:\doc\*.txt

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

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

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

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

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

rd MyFolder

удаление папки

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

ошибка при удаление папки

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

rd /s MyFolder

удаление папки с подтверждением

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

rd /s /q MyFolder

удаление папки без подтверждения

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

rd Folder1 Folder2

удаление нескольких папок

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

rd "My Files"

удаление папок с пробелом

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

Удаление файлов и папок в PowerShell

В консоли PowerShell вы можете использовать рассмотренные выше команды и , либо «» — собственную команду (командлет) PowerShell. С помощью данной команды можно удалять можно удалять файлы, папки, ключи реестра, переменные и другие объекты.

Например, для того чтобы удалить файл или папку в консоли PowerShell можно использовать команду:

Remove-item file.txt
Remove-item MyFolder

Удаление файлов в PowerShell

Создатель сайта comp-security.net, автор более 2000 статей о ремонте компьютеров, работе с программами, настройке операционных систем.

Задайте вопрос в комментариях под статьей или на странице
«Задать вопрос»
и вы обязательно получите ответ.

DEL (ERASE)

Формат командной строки:

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

/P – Запрос на подтверждение перед удалением каждого файла.

/F – Принудительное удаление файлов, доступных только для чтения.

/S – Удаление указанных файлов из всех подкаталогов.

/Q – Отключение запроса на подтверждение при удалении файлов.

/A – Отбор файлов для удаления по атрибутам.

S – Системные файлы
R – Доступные только для чтения
H – Скрытые файлы
A – Файлы для архивирования
Префикс “-” имеет значение НЕ – например -H – не скрытый файл.

erase D:\myfile.txt – удалить файл D:\myfile.txt
erase D:\ – удалить все файлы в корневом каталоге диска D:
erase D:\*.bak – удалить все файлы с расширением .bak
в корневом каталоге диска D:
erase D:\files – удалить все файлы в каталоге files диска D: – будут удалены
все файлы, не имеющие хотя бы один из атрибутов скрытый (H) , системный (S) и
только чтение ( R )
del /A:h d:\files\*.htm – удалить все файлы с расширением htm и атрибутом
скрытый в каталоге D:\files . Файлы, не имеющие атрибута скрытый или
имеющие, дополнительно к нему, другие атрибуты, удаляться не будут.
del /A:hsra d:\files\* – удалить все файлы с установленным набором атрибутов H , S, R, A


del d:\files\?d?.* – удалить файлы, имеющие в имени символ d и любое расширение.
del /S /F /Q %TEMP%\*.tmp – очистка каталога временных файлов.
Будут удалены все временные файлы с расширением .tmp в каталоге
для временных файлов и всех его подкаталогах без запроса на подтверждение
удаления.


Весь список команд CMD Windows

Команда RMDIR (RD) – удалить каталог файловой системы Windows.

RMDIR

RD

Формат командной строки:

/S – Удаление дерева каталогов, т. е. не только указанного каталога, но и всех содержащихся в нем файлов и подкаталогов.

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

Примеры использования команды RD ( RMDIR)

RD C:\Mydocs C:\Myprogs – выполнить удаление содержимого папок C:\Mydocs и C:\Myprogs.

RD C:\docs – выполнить удаление папки C:\docs. Если параметр /S не задан, то удаляемая папка C:\docs должна быть пустой.

RD /S /Q C:\Docs – удаление папки C:\Docs и всех ее подпапок без запроса на подтверждение.

Особенность реализации команды RD с параметром /S заключается в том, что будут удалены не только подкаталоги, но и сам каталог C:\Docs, даже если в нем существовали файлы, а не подпапки. Поэтому, для
удаления только содержимого каталога ( когда требуется сделать каталог пустым, а не удалить его совсем), можно воспользоваться следующим приемом – сделать
удаляемый каталог текущим и выполнить команду RD по отношению к его содержимому:


CD “My Folder”


RD /s/q “My Folder”

/S

Ниже приведенный командный файл удаляет пустые папки в каталоге временных файлов,
определяемом значением переменной окружения TEMP. Список удаленных папок записывается в файл с именем c:\tempfoldersempty.txt


FOR /D %%i in (*) do (


Весь список команд CMD Windows