Remove command windows command line

cmd Delete Folder – How to Remove Files and Folders in Windows

Sometimes it’s just faster to do things with the command line.

In this quick tutorial we’ll go over how to open Command Prompt, some basic commands and flags, and how to delete files and folders in Command Prompt.

If you’re already familiar with basic DOS commands, feel free to skip ahead.

How to open Command Prompt

To open Command Prompt, press the Windows key, and type in «cmd».

Then, click on «Run as Administrator»:

Screenshot showing how to open Command Prompt as an administrator

After that, you’ll see a Command Prompt window with administrative privileges:

command-prompt-new-window

Screenshot of Command Prompt window

If you can’t open Command Prompt as an administrator, no worries. You can open a normal Command Prompt window by clicking «Open» instead of «Run as Administrator».

The only difference is that you may not be able to delete some protected files, which shouldn’t be a problem in most cases.

How to delete files with the del command

Now that Command Prompt is open, use cd to change directories to where your files are.

I’ve prepared a directory on the desktop called Test Folder. You can use the command tree /f to see a, well, tree, of all the nested files and folders:

Screenshot after running tree /f in target directory

To delete a file, use the following command: del "<filename>".

For example, to delete Test file.txt, just run del "Test File.txt".

There may be a prompt asking if you want to delete the file. If so, type «y» and hit enter.

Note: Any files deleted with the del command cannot be recovered. Be very careful where and how you use this command.

After that, you can run tree /f to confirm that your file was deleted:

Screenshot after deleting file with del command

Also, bonus tip – Command Prompt has basic autocompletion. So you could just type in del test, press the tab key, and Command Prompt will change it to del "Test File.txt".

How to force delete files with the del command

Sometimes files are marked as read only, and you’ll see the following error when you try to use the del command:

Screenshot of error after trying to delete a read only file

To get around this, use the /f flag to force delete the file. For example, del /f "Read Only Test File.txt":

Screenshot after deleting file with the force flag

How to delete folders with the rmdir command

To delete directories/folders, you’ll need to use the rmdir or rd command. Both commands work the same way, but let’s stick with rmdir since it’s a bit more expressive.

Also, I’ll use the terms directory and folder interchangeably for the rest of the tutorial. «Folder» is a newer term that became popular with early desktop GUIs, but folder and directory basically mean the same thing.

To remove a directory, just use the command rmdir <directory name>.

Note: Any directories deleted with the rmdir command cannot be recovered. Be very careful where and how you use this command.

In this case I want to remove a directory named Subfolder, so I’ll use the command rmdir Subfolder:

Screenshot of a directory not empty error

But, if you remember earlier, Subfolder has a file in it named Nested Test File.

You could cd into the Subfolder directory and remove the file, then come back with cd .. and run the rmdir Subfolder command again, but that would get tedious. And just imagine if there were a bunch of other nested files and directories!

Like with the del command, there’s a helpful flag we can use to make things much faster and easier.

How to use the /s flag with rmdir

To remove a directory, including all nested files and subdirectories, just use the /s flag:

Screenshot after running rmdir with the /s flag

There will probably be a prompt asking if you want to remove that directory. If so, just type «y» and hit enter.

And that’s it! That should be everything you need to know to remove files and folders in the Windows Command Prompt.

All of these commands should work in PowerShell, which is basically Command Prompt version 2.0. Also, PowerShell has a bunch of cool aliases like ls and clear that should feel right at home if you’re familiar with the Mac/Linux command line.

Did these commands help you? Are there any other commands that you find useful? Either way, let me know over on Twitter.



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Cmd.exe is the command-line interpreter for Windows operating system. By using the command prompt, one can navigate to any file located on the computer.

As per the default Windows 7/8/10 installation, the command line will open the user’s home directory. This directory is usually “C:\Users\<username>” where “<username>” is the username selected during Windows setup.

Windows Command Line Delete Folder Prompt

Showing the contents of a directory

This folder holds the documents, pictures, desktop and downloads directories associated with the user. To list and display all files and folders in the command line, type “DIR” (short for directory). This will list all files and folders and associated attributes of those files like size, file attributes, created and modified date, etc.

How can you navigate to another folder through CMD

The first command in this aspect is the “cd” (Change Directory). The command helps the user in changing the current directory or folder from the current directory.

Note: Windows File System and Commands are not case sensitive. Hence, “cd” is the same as “CD”.

Windows Command Line Delete Folder CD Change Directory

Type “cd Desktop” to navigate the “Desktop” folder. This will show all the items on your Windows Desktop. Since only the folder name “Desktop” was specified, it is considered a relative folder name. Meaning Windows will look for a “Desktop” folder in the current folder only. Sub-folders or “Desktop” folders outside of the current folder are ignored.

To specific absolute folders, specify the full folder path. For example, “C:\Users\<username>\Desktop”.

It is possible to specify absolute folders starting from the correct location. Use the specific “.” operator to start from the correct folder and enter the remaining folder path after the dot. For example, “cd ./Documents”

The command “cd \” changes the directory to the root folder of the drive. If you are on the “C” drive, then “cd \” will take you to “C:\>” irrespective of the current folder.

If you want to navigate up to a folder, you will have to use the cd.. command.

Say you want to go to the “Users” folder. Assuming you are in the default folder “C:\Users\<username>”, type “cd..” and press Enter. This will change the current folder to “C:\Users”.

How to Delete Directories or Folders with CMD?

In the command line (cmd.exe), we use the “rmdir” command for deleting a folder. “rmdir” is short for “Remove Directory”. It is worth noting that “rmdir” deletes only directories. It will show an error if you try to erase a file with the command “rmdir”.

Type “rmdir <foldername>” to delete the folder. Take extra care behavior executing this command since you may lose important data.

If “rmdir” is used sans parameters, it will only remove empty folders.

Windows Command Line Delete Folder RMDIR remove directory

Using the “/s” parameter, we can erase a folder, sub-folders, and files inside the specified folder. For example, “rmdir /s c:\temp” will remove all files and folders inside the folder “temp” residing in the root directory “C:\”.

As it is a matter of deletion, the command line reconfirms if you want to really delete the folder/files. If you type “y”, the computer will take that to be the confirmation and continue to delete the specified folder.

If the folder to be deleted has a space in its name, enclose the name in double quotes like this: “rmdir “My Folder With Space In Name””

To delete a folder in a directory that is not owned by you, you should opt to start the command line tool as an administrator using the “Run as administrator” option. 

To “Run as administrator”, follow these steps:

  1. Press the “Windows” key to open the Windows “Start” menu
  2. Type “cmd” to search for the command-line tool
  3. “Command Prompt” should show up as the first search result
  4. Right-click on it and select “Run as Administrator”

While working with administration privileges and deleting files or folders, an extra level of caution is required as any wrong command can permanently crash your computer.

Deletion of Files with CMD

“del” command is used for deleting files in the command line tool (cmd.exe).

If you try to delete a file using “rmdir”, it will show an error. Similarly, if you try to delete a folder using the “del” command, it will also result in an error.

You need to just type “del” followed by filename and extension, to delete the file. For example, type “del temp.txt” to delete a file named “temp.txt” in the current folder.

Windows Command Line Delete Folder DEL delete file

You can also specify the file’s full path if the file to be deleted is not in the current folder.

Like “rmdir”, the “del” command will require administrator privileges if the file to be deleted and not owned by the current user.

If you want to delete multiple files at one go, you will have to enter the filenames consecutively. For example, “del temp.txt temp1.txt”.

Delete multiple files and folders at one go.

It is not always possible to enter all the file names or folder names while deleting them. It can be impractical due to multiple causes, and it doesn’t make any sense if there is a better way to do that.

The command-line tool supports wildcards that can act as placeholders and match multiple files or folders.

Asterix (*) is the most commonly used wildcard in the command-line tool. Asterix matches one or more characters. For example, “pop*” matches all names that start with “pop”. It will match “popcorn”, “popup”, and “pop corn”.

Similarly, “*pop*” matches “butter popcorn”, “repop” and “popcorn”. Essentially, matching anything that contains the word “pop” in it.

Type command “del pop*” will delete all matching files starting with the word “pop”.

To delete all text files, type “del *.txt”. This will match and delete all files that have the extension “.txt”.

Similarly, “rmdir /s *.*” will delete all folders, sub-folders, and files in the current folder. Be extremely careful while executing this command.

Summary

  • For navigating straight to the directory where the file is residing, you need to use the “cd” and “dir” commands.
  • To perform deletion of folders, use “rmdir” and delete files, use the “del” command. The folder or file name should be in quotes if it contains space in its name.
  • Wildcards can be used to delete multiple files and folders that match a specific pattern.

Related Posts

  • How to Factory Reset a Toshiba Laptop Yourself
  • How To Fix Headphones When Only One Side Works
  • How To Fix Cursor or Mouse Pointer Disappears in Google Chrome Browser
  • Best Video Player For Windows 10 PC
  • How To Use iMac As Monitor – Target Display Mode
  • Useful shortcuts equivalents on MacBook Air with Windows 7
  • How To Fix The “This Site Can’t Be Reached” Error In Google Chrome – Windows/Mac/Linux
  • How To Fix “Server IP Address Could Not Be Found”
  • Installing Windows 7 on MacBook Air
  • Service Host SysMain causing high disk or high CPU usage?

Командная строка – мощный инструмент для автоматизации и упрощения многих задач, которые возникают при администрировании компьютера с операционной системой 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

The rm command is a basic command on Unix/Unix-like OS to remove files, directors, and symbolic links. The rm command, short for remove, is similar to the del command in Windows, which is used to remove files you no longer need.

the rm command

The rm command is generally enclosed in some wrapper in case of accidental deletion because files deleted by the rm command can’t be easily restored from recycle bin or Trash.

So, after intentionally or unintentionally deleting files by the rm command, you should use data recovery software to get the deleted files back, or you can restore them from your precious backups.

The rm command Linux removes the specified file parameter from a directory. And the deletion of files by the command doesn’t require permission to read or write. Instead, you must be permitted to write for the file’s directory.

Delete Files Using rm Command on Linux, Windows, and Mac

Suppose you want to use the rm command to delete files on Linux, Windows, or Mac. In that case, the first thing is to make sure you have the write permission for the directory contents, so you can use the rm command to remove the entire files or select files from a list within a directory. Like this:

rm [Option]…FILE…

Here are some options to specify how the rm command will behave:

  • The -d flag empty directories and only works when the specified directory is empty.
  • The -e flag displays a message after each file is deleted.
  • The -f flag ignores non-existent files and overrides any confirmation prompts.
  • The -i flag asks for every deletion to be confirmed.
  • The -r flag removes directories. This flag is equivalent to the -R flag.
  • The -v flag prints what the rm command is doing onto the Terminal.

Suppose you want to delete a large number of files without confirmation. In that case, you can manually cancel out the «-i» argument by adding the «-f» option, as the option specified later on in the expanded command line «rm -i -f» takes precedence.

Share this article on social media to help others learn more about the rm command on Linux, Windows, and Mac.

🐧rm Command: Examples on Linux

Suppose the file name is «testfile1». Type the following to delete the «testfile1»:

rm testfile1

To delete all the files in the target directory one by one, type the following:

rm -i tragetdir/*

And to remove a file that is not in the current directory, you should mention the path and type rm followed by the path:

rm ~/Documents/testfile3.txt

This command will remove the file named «testfile3» located in the Documents directory.

🪟rm Command: Examples on Windows

To delete a non-empty folder on Windows PC using CMD, you may probably get the error «The directory is not empty». And you could force the rmdir command to delete this non-empty folder and execute the deletion as follows:

C:\> rmdir /s /q

The /s option means deleting the folder with its sub-folders and files.

The /q option means no prompt for confirmation.

🍏rm Command: Examples on Mac

Suppose your computer runs macOS; In the Terminal window, type rm and drag the file you want to delete into the Terminal window, then press «Enter». For example, the rmdir Pictures would delete the directory «Pictures» from the directory you are currently in.

recover rm deleted files on Mac

How to Recover Files Deleted by RM on Mac

RM or RM — R command is used in Mac Terminal to delete files permanently, and this article will tell you effective ways to recover your deleted files. Read more >>

Can I Recovery Files Deleted by rm Command

It is typically impossible to undo the rm command after it is executed. The rm command deletes files permanently, and the deleted files will not be found in the Recycle Bin on your Windows PC or Trash on your Mac.

🧑‍🔧Recover Files Deleted by rm Command Using Data Recovery Software on Windows

However, some command line tools and data recovery software can help recover files deleted by the rm command, such as a powerful data recovery software EaseUS Data Recovery Wizard, which can recover various file types under numerous situations effectively and easily.

To easily understand the operation of the EaseUS data recovery software, you can refer to the steps below:

Step 1. Install and open the EaseUS data recovery software on your computer, and choose the partition where your deleted files are stored on.

Step 2. Click «Scan» to view all the deleted files, including files deleted by the rm command.

Step 3. Select files you want to restore, click «Preview» to view their content, and click «Recover» to get them back.

⏱️Recover Files Deleted by rm Command from Time Machine on Mac

In addition, you can recover files deleted by the rm command on Mac from the previous backups, such as the Time Machine Backup Schedule on Mac. Follow the steps below:

Step 1. Open «System Preferences» and find «Time Machine».

Step 2. Turn on the «Show Time Machine in the menu bar» option in the Time Machine window.

Step 3. Click «Enter Time Machine» on the Apple menu bar, and use the arrow buttons to locate the snapshot which contains the deleted files.

Step 4. Select the files and folders you want to undelete and click «Restore» to return them to their original locations.

⚠️Recover Files Deleted by rm Command Using CMD

Note that using the attrib command in CMD only allows you to unhide files instead of recovering deleted files. If the rm command permanently deletes your files, the CMD won’t be helpful, and you need to use EaseUS Data Recovery Wizard as a CMD alternative.

Follow the steps below to unhide your files using CMD:

Step 1. Press «Windows + X» and hit on the «Command Prompt (Admin)» option in the menu.

Note: For Windows 8 and Windows 7, you should press «Windows + R» to find «Command Prompt Admin».

Step 2. Type chkdsk ‘drive letter:’/f, press «Enter», and press «Y», and wait for the command lines to start again.

Step 3. Type drive letter again, hit «Enter», and type [drive letter: \ >attrib -h -r -s/s /d *.*].

Conclusion

The rm command is a basic Linux command that can remove files, directors, and symbolic links. The rm command is enclosed in default in case of accidental deletion.

Suppose the rm command deletes your files. In this case, if you want to restore the deleted files, three methods are suggested: recovering the deleted files using CMD, using data recovery software, such as EaseUS Data Recovery Wizard, and recovering from previous backups.

rm Command FAQs

Here are some questions people also ask when they search for the rm command, and you can read the questions below to learn more about the rm command:

1. How to delete files using cmd?

Follow the steps below to delete files using CMD:

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.

2. What is the rm rf command?

The rm -rf command allows removing root-owned files and directories. The rm command is a Linux command for removing files/directories. The -r option indicates recursive removal and removes non-empty directories. The -f option allows removal without confirmation.

3. How do I recover files after the rm command?

You can recover files deleted by the rm command using data recovery software like EaseUS Data Recovery Wizard, using CMD, and using your previous backups.

4. Does the rm command delete a directory?

The rm command can be used to delete a directory entirely, which means, this command deletes a directory and all files or subdirectories within this directory.

  • Remove activate windows watermark windows 10
  • Regsvr32 initpki dll не удалось загрузить модуль windows 7
  • Removable storage devices папка на рабочем столе windows 10 как удалить
  • Remote desktop connections windows 10
  • Remotefx windows server 2008 r2