Как удалить файл через консоль в windows 10

Все способы:

  • Способ 1: Закрытие связанного процесса
  • Способ 2: «Командная строка»
  • Способ 3: Изменение владельца файла
  • Способ 4: Загрузка в «Безопасном режиме»
  • Способ 5: Переименование файла
  • Способ 6: Функции архивирования
  • Способ 7: Сторонние программы
  • Вопросы и ответы: 0

Способ 1: Закрытие связанного процесса

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

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

Если же программа нигде не отображается, то выключить ее можно через «Диспетчер задач»:

  1. Откройте «Диспетчер задач». Проще всего кликнуть правой кнопкой мыши по нижней рабочей панели и запустить приложение через контекстное меню.
  2. как принудительно удалить файл в windows 10-02

  3. На вкладке «Процессы» отыщите проблемную программу. Если необходимо, можно упорядочить названия по имени, кликнув по названию столбца вверху. Выделите приложение, затем выберите кнопку «Снять задачу». Для детального поиска процесса можно переключиться на вкладку «Подробности» и поискать там.
  4. как принудительно удалить файл в windows 10-03

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

Читайте также: Методы принудительного удаления программ в Windows 10

Способ 2: «Командная строка»

Принудительно удалить файл в Windows 10 можно через встроенную консоль, использовав специальную команду и указав путь к нему. Метод может сработать, даже если файл открыт, но из-за сбоев в системе не получается его закрыть.

  1. Через «Проводник» перейдите к расположению файла. Если он находится на рабочем столе или в папке «Загрузки», то указывать нужно путь на диске C через персональную папку (то есть, например, C:\Users\ИМЯ_ПОЛЬЗОВАТЕЛЯ\Downloads). Скопируйте адрес из верхней строки, кликнув по ней правой кнопкой мыши и выбрав пункт «Копировать».
  2. как принудительно удалить файл в windows 10-04

  3. Запустите «Командную строку» с расширенными правами, нажав на «Пуск» и введя в нем название приложения. Среди результатов выберите открытие от имени администратора.
  4. как принудительно удалить файл в windows 10-05

  5. В консоли введите del /f /s /q /a, затем поставьте пробел, откройте кавычки и вставьте путь к файлу, поставьте обратный слэш (\) и впишите точное название удаляемого файла с его расширением, после чего закройте кавычки. К примеру, если файл находится на рабочем столе, в нашем примере команда будет выглядеть так: del /f /s /q /a «C:\Users\Professional\Desktop\документ.docx», где «Professional» — имя нашей учетной записи. Нажмите на клавишу «Enter», чтобы подтвердить удаление.
  6. как принудительно удалить файл в windows 10-06

В результате отобразится сообщение, что файл удален, причем при таком подходе он будет стерт без временного помещения в «Корзину».

Способ 3: Изменение владельца файла

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

  1. Щелкните правой кнопкой мыши по названию файла, чтобы вызвать контекстное меню. Перейдите в раздел «Свойства».
  2. как принудительно удалить файл в windows 10-07

  3. В новом окне нажмите на вкладку «Безопасность», затем на кнопку «Дополнительно».
  4. как принудительно удалить файл в windows 10-08

  5. На строке «Владелец» кликните по ссылке «Изменить».
  6. как принудительно удалить файл в windows 10-09

  7. Введите имя своей учетной записи в специальное поле и щелкните по кнопке подтверждения.
  8. как принудительно удалить файл в windows 10-10

Закройте все окна раздела со свойствами и попробуйте снова удалить файл.

Способ 4: Загрузка в «Безопасном режиме»

Когда сторонние программы мешают удалению файла или это не получается сделать из-за вирусов, которые проникли в систему, может помочь загрузка Windows 10 в «Безопасном режиме»:

  1. Откройте средство «Конфигурация системы» с помощью диалогового окна «Выполнить». Одновременно нажмите клавиши «Win + R», затем напишите команду msconfig и кликните по «ОК».
  2. как принудительно удалить файл в windows 10-11

  3. Перейдите на вкладку «Загрузка». В блоке «Параметры загрузки» отметьте пункт «Безопасный режим» и выберите параметр «Минимальная», при которой система будет запущена лишь только с критически необходимым количеством драйверов, служб и программ. Нажмите на «Применить».
  4. как принудительно удалить файл в windows 10-12

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

Читайте также: Выход из «Безопасного режима» на Windows 10

Способ 5: Переименование файла

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

Переименуйте файл, используя функцию контекстного меню. Также можно попробовать изменить его расширение: после точки, отделяющей название от формата, впишите другое расширение, например измените .docx .zip.

как принудительно удалить файл в windows 10-13

Способ 6: Функции архивирования

Некоторые архиваторы позволяют тонко настраивать процедуру архивирования файлов, в том числе удалять оригинал после завершения процедуры. Другими словами, вам понадобится заархивировать проблемные данные, выбрать соответствующую функцию в программе, а потом избавиться от самого архива. В этом может помочь бесплатный софт, например 7-Zip.

Скачать 7-Zip

  1. Установите архиватор. Его функции автоматически интегрируются в контекстное меню. Щелкните по файлу правой кнопкой мыши, наведите курсор на пункт «7-Zip» и из дополнительного списка выберите «Добавить к архиву…».
  2. как принудительно удалить файл в windows 10-14

  3. В окне с настройками архива найдите блок «Опции» и отметьте пункт «Удалять файлы после сжатия». Нажмите на «ОК».
  4. как принудительно удалить файл в windows 10-15

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

Способ 7: Сторонние программы

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

Подробнее: Программы для удаления файлов, которые не удаляются

как принудительно удалить файл в windows 10-16

Наша группа в TelegramПолезные советы и помощь

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.

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

In some cases, Windows is not allowing some users to delete their files or folders. You can use the command prompt to delete a file or a folder if you encounter such a problem. In this article, we will show you how exactly you can use this method to delete files and folders.

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

To use this method do the following:

  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:

You want to delete a file called Info.txt that is located on your desktop. Use the following command in the Command Prompt where you replace username with your own username:

Del “C:\Users\username\Desktop\Info.txt”

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.

To use this command do the following:

  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

For example, to delete a folder named “Info” on your desktop, use the following command where you will replace username with your own username:

rmdir “C:\Users\username\Desktop\Info”

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.

Post Views: 48,867

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

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

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Как удалить системные разделы жесткого диска с windows 10
  • Какие службы включить для сетевого обнаружения windows 10
  • Служба теневого копирования тома не работает 0x81000203 windows 10
  • Asus x401a drivers windows 10
  • Mtp usb samsung driver windows 7