Как удалить файл при помощи командной строки windows

Last Updated :
16 May, 2024

While working on Windows devices, we used to work on Windows File Explorer for working with files. On File Explorer of Windows, the creation of new files as well as deleting old ones is one of the easiest processes. However, if your File Explorer is not responding, then the process to Delete Folder using CMD can be an alternative.

The Windows Command Prompt is the command line tool that executes different tasks with the help of Windows Commands. Using CMD in Windows, the File Creation for Windows can also be executed. If you are having trouble Deleting Files or Folders on Windows directly by right-clicking, then you can Delete files using CMD.

This article is going to discuss the commands required to Remove Files & Folders using the UsingCommand Prompt of Windows.

Table of Content

  • Methods to Delete Files and Folders Using Command Prompt
    • Method 1: Delete Files or Folders on CMD using DEL Command
    • Method 2: Delete Files or Folders on CMD using RMDIR Command
  • Delete a Folder and Subfolders in Command Prompt

Methods to Delete Files and Folders Using Command Prompt

To Erase Windows Files or Folders using CMD, the following guidelines should be used properly. Let us start with the DEL Command Execution.

Method 1: Delete Files or Folders on CMD using DEL Command

Note: DEL Command is used to delete a file. Here, we will take our sample file “hello.txt” located on 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 and press Enter.

cd desktop

Step 2: Delete the file hello.txt with the following Windows Command.

del hello.txt

1--DEL-Command

Method 2: Delete Files or Folders on CMD using RMDIR Command

Note: RMDIR Command is used to delete the entire folder or directory. Here, we will take our sample folder named “Tasks” placed on the desktop and try to delete it using RMDIR Command in CMD.

Step 1: Change the Directory’s Path in Command Prompt and set it to the path of the folder.

cd desktop

Step 2: Delete the folder Tasks with the following command.

rmdir tasks

2--RMDIR-Command

From the above discussion, this should become clear that the Deletion of Windows Files using CMD is a matter of a few seconds. You have to just move inside the Windows Directory using the Windows CD Command. And then, as per your choice execute any one of the Windows File Deletion Commands in CMD.

Delete a Folder and Subfolders in Command Prompt

Step 1: Open Command Prompt.

Step 2: Navigate to the directory where the folder you want to delete is located using the cd command.

Command:   cd <FolderName>

Step 3: To delete a single folder, use the following command.

Command: rmdir <FolderName>

Step 4: To delete a folder and all its subfolders and files, just include “/s” in between the rmdir and <folderName>, use the following command.

Command: rmdir /s <FolderName>

Step 5: Press Enter to execute the command.

Also Read

  • Useful CMD commands for daily use in Windows OS
  • CMD Commands to Gather Information of a System
  • How to Show all the previously connected WiFi Networks using CMD in Windows?

Conclusion

In this article, we explored how to use Command Prompt in Windows to delete files and folders efficiently when facing issues with File Explorer. We discussed two methods: using the DEL command to delete files and the RMDIR command to delete folders. Additionally, we provided a step-by-step guide on how to delete folders and subfolders using Command Prompt.

Загрузить PDF

Загрузить PDF

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

  1. Step 1 Выберите файл.

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

    • Если вы не знаете, где находится файл, введите его имя в строке поиска меню «Пуск», затем щелкните по нему правой кнопкой мыши и в меню выберите «Расположение файла», чтобы перейти непосредственно к файлу.
  2. Step 2 Перетащите файл на рабочий стол.

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

    • Исключением из этого правила является случай удаления файла из папки «System32», которая является системной папкой Windows. В этом случае оставьте файл в этой папке.
  3. Step 3 Щелкните по файлу правой кнопкой мыши.

    Откроется выпадающее меню.

  4. Step 4 Нажмите Свойства.

    Эта опция находится в нижней части открывшегося меню.

  5. Step 5 Выясните расширение файла.

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

    • .txt – текстовые файлы (созданы в Блокноте).
    • .docx – файлы Microsoft Word.
    • .jpg or .png – изображения.
    • .mov, .wmv, .mp4 – видеофайлы.
    • .mp3, .wav – аудиофайлы.
    • .exe – исполняемые файлы (например, установочные файлы).
    • .lnk – ярлыки. Удаление ярлыка не приведет к удалению соответствующего файла (программы).
  6. Step 6 Запишите расширение файла.

    Теперь можно открыть и воспользоваться командной строкой.

    Реклама

  1. Step 1 Откройте командную строку.

    Открыть командную строку нужно без административных прав, если только вы не собираетесь удалять файл из системной папки «System32». Открыть командную строку можно по-разному в зависимости от версии Windows:

    • Зажмите клавишу Win, нажмите X, а затем над кнопкой «Пуск» нажмите «Командная строка».
    • Щелкните правой кнопкой мыши по кнопке «Пуск» (в левом нижнем углу экрана) и в меню выберите «Командная строка».
    • В строке поиска меню «Пуск» введите «Командная строка» (без кавычек; в Windows 8 переместите курсор мыши в правый верхний угол экрана и щелкните по значку в виде лупы) и нажмите «Командная строка», когда появится соответствующий значок.
    • В меню «Пуск» нажмите «Выполнить», введите «cmd» (без кавычек) и нажмите «OK».
  2. Step 2 Введите cd desktop и нажмите Enter.

    Так в командой строке вы перейдете в каталог, соответствующий рабочему столу.

    • Если нужно, воспользуйтесь другими методами, чтобы изменить каталог в командной строке.
    • Если открыть командную строку в качестве администратора, вы автоматически переместитесь в каталог (папку) «System32». Поэтому не открывайте командную строку с административными правами, только если удаляемый файл не находится в папке «System32».
  3. Step 3 Введите del [имя.расширение].

    Замените «имя.расширение» на имя и расширение удаляемого файла.

    • Например, если нужно удалить изображение под названием «icecream», введите icecream.png, а если текстовый файл под названием «notes», введите notes.txt (и так далее).
    • Если в имени файла есть пробелы, имя и расширение файла нужно заключить в кавычки: "I like turtles.jpg" вместо I_like_turtles.jpg.
    • Чтобы удалить с рабочего стола все файлы с одинаковым расширением (например, все текстовые файлы), введите *.расширение, где вместо «расширение» подставьте соответствующее расширение (например, *.txt).
  4. Step 4 Нажмите ↵ Enter.

    В командной строке появится новая пустая строка.

    • Команда «del» удаляет файлы непосредственно с жесткого диска, то есть не нужно повторно удалять их из Корзины.

    Реклама

Советы

  • Чтобы удалить файлы, лучше воспользоваться файловым менеджером. С помощью командной строки удаляйте файлы, от которых сложно избавиться.

Реклама

Предупреждения

  • Удаление системного файла может привести к краху системы.
  • Файлы, которые удаляются через командную строку, в Корзину не попадают.

Реклама

Об этой статье

Эту страницу просматривали 89 404 раза.

Была ли эта статья полезной?

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:

Image

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

on August 5, 2015

Deleting files is one of the frequently done operation from Windows command prompt. This post explains how to use ‘del’ command from CMD for different use cases like deleting a single file, deleting files in bulk using wild cards etc. Before we start to look at the syntax, note that the command works only for files and can’t handle folders.

How to delete a file

Run del command with the name of the file to be deleted, you are done!

del filename

You do not see message after running the command if the file is deleted successfully. Error message is shown only when something goes wrong.

Delete files in bulk

Del command recognizes wildcard(*) and so can be used to delete files in bulk from CMD.  Some examples below.
To delete all the files in current folder

del *

To delete all the files with ‘log’ extension

del *.log

Delete all files having the prefix ‘abc’

del abc*

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

del *PIC*

The above are the basic use cases of del command. Continue to read below for non trivial use cases.

Delete multiple files

‘Del’ command can accept multiple files as argument

del filename1 filename2 filename3 filename4....

Example:

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

Delete Read only files

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

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

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

del /F readonlyfile.txt

Alternatively, we can use the below command too

del /A:R readonlyfile.txt

Windows 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

Step 3. Right-click cmd and select «Run as Administrator».

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

How to Use  CMD Delete File with del

Once you have learned how to open the Command Prompt, you can type in command lines. Follow the tutorial and type in the correct command lines to delete files.

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

You will need a different command to delete folders with cmd on your computer. Keep reading and follow the operations:

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.

No matter it is you delete file with PowerShell or with Command Prompt, EaseUS Data Recovery Wizard can help you recover deleted files easily. This professional recovery tool also can be handy for home users.

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. Run EaseUS Data Recovery Wizard. Choose the drive where you lost files and start scanning by clicking «Search for Lost Data». This software allows you to recover lost data from all devices, including HDD, SSD, USB drive, SD card, pen drive, camera, etc.

select a location to scan

Step 2. Browse the full scan results. You can choose the file type you need by clicking on the file type filter. EaseUS data recovery software supports 1000+ file types like photos, videos, documents, emails, audio files, and many more. 

Choose files to recover

Step 3. Select the files you want to preview. Click «Recover» and set a storage location or Cloud drive to save the recovered data. 

Recover lost data

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).

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Запуск службы восстановления windows 10
  • Windows open на весь экран
  • Windows 10 кооперативная код активации
  • Windows xp embedded русификация
  • Как установить windows 11 на несовместимый ноутбук