Удаление файлов через консоль windows

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

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

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

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

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

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

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

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

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

del test.txt

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

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

del e:\tmp\test.txt

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

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

del /p test.txt

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

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

del /F /A:R *.txt

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

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

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

del D:\

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

del D:\*.txt

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

del D:\doc

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

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

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

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

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

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

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

rd MyFolder

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

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

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

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

rd /s MyFolder

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

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

rd /s /q MyFolder

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

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

rd Folder1 Folder2

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

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

rd "My Files"

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

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

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

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

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

Remove-item file.txt

Remove-item MyFolder

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

Посмотрите также:

  • Выключение компьютера через командную строку
  • Как перезагрузить компьютер через командную строку
  • Как вызвать командную строку в Windows 7
  • Как поменять дату в Windows 7
  • Как выключить компьютер через определенное время

Автор
Александр Степушин

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

Остались вопросы?

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

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

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.

None of the answers as posted on 2018-06-01, with the exception of the single command line posted by foxidrive, really deletes all files and all folders/directories in %PathToFolder%. That’s the reason for posting one more answer with a very simple single command line to delete all files and subfolders of a folder as well as a batch file with a more complex solution explaining why all other answers as posted on 2018-06-01 using DEL and FOR with RD failed to clean up a folder completely.


The simple single command line solution which of course can be also used in a batch file:

pushd "%PathToFolder%" 2>nul && ( rd /Q /S "%PathToFolder%" 2>nul & popd )

This command line contains three commands executed one after the other.

The first command PUSHD pushes current directory path on stack and next makes %PathToFolder% the current directory for running command process.

This works also for UNC paths by default because of command extensions are enabled by default and in this case PUSHD creates a temporary drive letter that points to that specified network resource and then changes the current drive and directory, using the newly defined drive letter.

PUSHD outputs following error message to handle STDERR if the specified directory does not exist at all:

The system cannot find the path specified.

This error message is suppressed by redirecting it with 2>nul to device NUL.

The next command RD is executed only if changing current directory for current command process to specified directory was successful, i.e. the specified directory exists at all.

The command RD with the options /Q and /S removes a directory quietly with all subdirectories even if the specified directory contains files or folders with hidden attribute or with read-only attribute set. The system attribute does never prevent deletion of a file or folder.

Not deleted are:

  1. Folders used as the current directory for any running process. The entire folder tree to such a folder cannot be deleted if a folder is used as the current directory for any running process.

  2. Files currently opened by any running process with file access permissions set on file open to prevent deletion of the file while opened by the running application/process. Such an opened file prevents also the deletion of entire folder tree to the opened file.

  3. Files/folders on which the current user has not the required (NTFS) permissions to delete the file/folder which prevents also the deletion of the folder tree to this file/folder.

The first reason for not deleting a folder is used by this command line to delete all files and subfolders of the specified folder, but not the folder itself. The folder is made temporarily the current directory for running command process which prevents the deletion of the folder itself. Of course this results in output of an error message by command RD:

The process cannot access the file because it is being used by another process.

File is the wrong term here as in reality the folder is being used by another process, the current command process which executed command RD. Well, in reality a folder is for the file system a special file with file attribute directory which explains this error message. But I don’t want to go too deep into file system management.

This error message, like all other error messages, which could occur because of the three reasons written above, is suppressed by redirecting it with 2>nul from handle STDERR to device NUL.

The third command, POPD, is executed independently of the exit value of command RD.

POPD pops the directory path pushed by PUSHD from the stack and changes the current directory for running the command process to this directory, i.e. restores the initial current directory. POPD deletes the temporary drive letter created by PUSHD in case of a UNC folder path.

Note: POPD can silently fail to restore the initial current directory in case of the initial current directory was a subdirectory of the directory to clean which does not exist anymore. In this special case %PathToFolder% remains the current directory. So it is advisable to run the command line above not from a subdirectory of %PathToFolder%.

One more interesting fact:
I tried the command line also using a UNC path by sharing local directory C:\Temp with share name Temp and using UNC path \\%COMPUTERNAME%\Temp\CleanTest assigned to environment variable PathToFolder on Windows 7. If the current directory on running the command line is a subdirectory of a shared local folder accessed using UNC path, i.e. C:\Temp\CleanTest\Subfolder1, Subfolder1 is deleted by RD, and next POPD fails silently in making C:\Temp\CleanTest\Subfolder1 again the current directory resulting in Z:\CleanTest remaining as the current directory for the running command process. So in this very, very special case the temporary drive letter remains until the current directory is changed for example with cd /D %SystemRoot% to a local directory really existing. Unfortunately POPD does not exit with a value greater 0 if it fails to restore the initial current directory making it impossible to detect this very special error condition using just the exit code of POPD. However, it can be supposed that nobody ever runs into this very special error case as UNC paths are usually not used for accessing local files and folders.

For understanding the used commands even better, open a command prompt window, execute there the following commands, and read the help displayed for each command very carefully.

  • pushd /?
  • popd /?
  • rd /?

Single line with multiple commands using Windows batch file explains the operators && and & used here.


Next let us look on the batch file solution using the command DEL to delete files in %PathToFolder% and FOR and RD to delete the subfolders in %PathToFolder%.

@echo off
setlocal EnableExtensions DisableDelayedExpansion

rem Clean the folder for temporary files if environment variable
rem PathToFolder is not defined already outside this batch file.
if not defined PathToFolder set "PathToFolder=%TEMP%"

rem Remove all double quotes from folder path.
set "PathToFolder=%PathToFolder:"=%"

rem Did the folder path consist only of double quotes?
if not defined PathToFolder goto EndCleanFolder

rem Remove a backslash at end of folder path.
if "%PathToFolder:~-1%" == "\" set "PathToFolder=%PathToFolder:~0,-1%"

rem Did the folder path consist only of a backslash (with one or more double quotes)?
if not defined PathToFolder goto EndCleanFolder

rem Delete all files in specified folder including files with hidden
rem or read-only attribute set, except the files currently opened by
rem a running process which prevents deletion of the file while being
rem opened by the application, or on which the current user has not
rem the required permissions to delete the file.
del /A /F /Q "%PathToFolder%\*" >nul 2>nul

rem Delete all subfolders in specified folder including those with hidden
rem attribute set recursive with all files and subfolders, except folders
rem being the current directory of any running process which prevents the
rem deletion of the folder and all folders above, folders containing a file
rem opened by the application which prevents deletion of the file and the
rem entire folder structure to this file, or on which the current user has
rem not the required permissions to delete a folder or file in folder tree
rem to delete.
for /F "eol=| delims=" %%I in ('dir "%PathToFolder%\*" /AD /B 2^>nul') do rd /Q /S "%PathToFolder%\%%I" 2>nul

:EndCleanFolder
endlocal

The batch file first makes sure that environment variable PathToFolder is really defined with a folder path without double quotes and without a backslash at the end. The backslash at the end would not be a problem, but double quotes in a folder path could be problematic because of the value of PathToFolder is concatenated with other strings during batch file execution.

Important are the two lines:

del /A /F /Q "%PathToFolder%\*" >nul 2>nul
for /F "eol=| delims=" %%I in ('dir "%PathToFolder%\*" /AD /B 2^>nul') do rd /Q /S "%PathToFolder%\%%I" 2>nul

The command DEL is used to delete all files in the specified directory.

  • The option /A is necessary to process really all files including files with the hidden attribute which DEL would ignore without using option /A.
  • The option /F is necessary to force deletion of files with the read-only attribute set.
  • The option /Q is necessary to run a quiet deletion of multiple files without prompting the user if multiple files should be really deleted.
  • >nul is necessary to redirect the output of the file names written to handle STDOUT to device NUL of which can’t be deleted because of a file is currently opened or user has no permission to delete the file.
  • 2>nul is necessary to redirect the error message output for each file which can’t be deleted from handle STDERR to device NUL.

The commands FOR and RD are used to remove all subdirectories in specified directory. But for /D is not used because of FOR is ignoring in this case subdirectories with the hidden attribute set. For that reason for /F is used to run the following command line in a separate command process started in the background with %ComSpec% /c:

dir "%PathToFolder%\*" /AD /B 2>nul

DIR outputs in bare format because of /B the directory entries with attribute D, i.e. the names of all subdirectories in specified directory independent on other attributes like the hidden attribute without a path. 2>nul is used to redirect the error message output by DIR on no directory found from handle STDERR to device NUL.

The redirection operator > must be escaped with the caret character, ^, on the FOR command line to be interpreted as a literal character when the Windows command interpreter processes this command line before executing the command FOR which executes the embedded dir command line in a separate command process started in the background.

FOR processes the captured output written to handle STDOUT of a started command process which are the names of the subdirectories without path and never enclosed in double quotes.

FOR with option /F ignores empty lines which don’t occur here as DIR with option /B does not output empty lines.

FOR would also ignore lines starting with a semicolon which is the default end of line character. A directory name can start with a semicolon. For that reason eol=| is used to define the vertical bar character as the end-of-line character which no directory or file can have in its name.

FOR would split up the line into substrings using space and horizontal tab as delimiters and would assign only the first space/tab delimited string to specified loop variable I. This splitting behavior is not wanted here because of a directory name can contain one or more spaces. Therefore delims= is used to define an empty list of delimiters to disable the line splitting behavior and get assigned to the loop variable, I, always the complete directory name.

Command FOR runs the command RD for each directory name without a path which is the reason why on the RD command line the folder path must be specified once again which is concatenated with the subfolder name.

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

  • del /?
  • dir /?
  • echo /?
  • endlocal /?
  • for /?
  • goto /?
  • if /?
  • rd /?
  • rem /?
  • set /?
  • setlocal /?

In some cases, for whatever reason, Windows will make sure that the provided file is used by the system and prevent it from being deleted. This file situation is very frustrating, especially if you know the file is not in use.

If you are having trouble in deleting any file or folder directly by right-clicking, then you can delete it using cmd. The commands below delete the specific file or folder and place them in the recycle bin:

  • del
  • rmdir

Here we have created a sample File and a Folder to delete it using CMD:

del command

del command is used to delete a file. Here, we will take our sample file “hello.txt” located at the desktop and try to delete it using the del command in CMD. Follow the steps given below to delete the file:

Step 1: Change the path of the directory in CMD and set it to the path of the file. Type the following command in cmd and press Enter:

cd desktop

Step 2: Delete the file “hello.txt” with following command:

 del hello.txt

rmdir command

rmdir command is used to delete the entire folder or directory. Here, we will take our sample folder named “Tasks” placed at desktop and try to delete it using rmdir command in CMD. Follow the steps given below to delete the folder:

Step 1: Change the path of the directory in CMD and set it to the path of the folder. Type the following command in cmd and press Enter:

cd desktop

Step 2: Delete the folder “Tasks” with following command:

rmdir tasks

Last Updated :
03 Jul, 2022

Like Article

Save Article

  • Удаленная установка программ windows server
  • Удаление файлов по маске windows
  • Удаление файлов из реестра windows 10
  • Удаление следов usb устройств из реестра windows 7
  • Удаленное включение компьютера windows 10