Можно ли удалить папку windows powershell

Updated March 6, 2023

PowerShell Delete Folder

Introduction to PowerShell Delete Folder

PowerShell folder delete operation is to remove the folder from the specified location, whether its local path or the shared path using the cmdlet Remove-Item or other .Net approach, which performs to delete the folders or the subfolders and their contents and uses the specific switches to deal with the different types of the folder attributes like Read-only, hidden, etc to remove them.

Syntax of PowerShell Delete Folder

PowerShell uses various methods to delete the folders from the Windows operating system.

1. PowerShell Remove-Item Method

Syntax:

Remove-Item

[-Path] <String[]>
[-Filter <String>]
[-Include <String[]>]
[-Exclude <String[]>]
[-Recurse]
[-Force]
[-Credential <PSCredential>]
[-WhatIf]
[-Confirm]
[-Stream <String[]>]
[<CommonParameters>]

Remove-Item

-LiteralPath <String[]>
[-Filter <String>]
[-Include <String[]>]
[-Exclude <String[]>]
[-Recurse]
[-Force]
[-Credential <PSCredential>]
[-WhatIf]
[-Confirm]
[-Stream <String[]>]
[<CommonParameters>]

From the above sets, you can use the combination of one only. You can’t use -Path and -LiteralPath both in the same command.

2. Command Prompt

  • Using rmdir command

rmdir [<drive>:]<path> [/s [/q]]

  • Using del

del [/p] [/f] [/s] [/q] [/a[:]<attributes>] <names>
erase [/p] [/f] [/s] [/q] [/a[:]<attributes>] <names>

3. FileSystem Object Method

Using the FileSystem Object Method. We can create a file system object and use the DeleteFolder method.

object.DeleteFolder folderspec, [ force ]

4. Using .Net Class Approach

[System.IO.Directory] .Net class uses the method Delete() folder.

[System.IO.Directory]::Delete(String)
[System.IO.Directory]::Delete(String,Boolean)

How to Delete Folders in the PowerShell?

As shown in the syntax, PowerShell uses various methods like Native command Remove-Item, cmd commands rmdir and del, File System Object method, and .Net approach to delete the files from the folder.

Window System folder has various attributes associated with it like Read-Only, Hidden, Archive, etc, and to delete them we may need the various parameters to pass in the cmdlet.

Examples to Implement of PowerShell Delete Folder

Below we discuss examples of PowerShell Delete Folder:

Example #1

Remove-Item to delete the folder with Subfolders and files

Consider we have a folder stored at the location C:\temp\Test\ and we need to delete that folder using the Remove-Item command. The folder contains the below items.

Command:

Get-ChildItem C:\Temp\Test\

Output:

PowerShell Delete Folder Example 1

To remove the items,

Remove-Item C:\Temp\Test\ -Verbose

Once you run this command, it will ask for confirmation.

Confirmation Example

You can press ‘Yes’ every time or ‘Yes to All’ to confirm all the files and folders.

This prompt is generated because the Test folder contains the subfolders and files, use the -Recurse Parameter to delete all the inside files and folders and -Force parameter to delete them forcefully.

Remove-Item C:\Temp\Test\ -Recurse -Force -Verbose

Output:

Recurse Paramete Example 3

Example #2

Use -WhatIF parameter With Remove-Item to avert wrong folder deletion. We can use -WhatIf parameter that shows which files and folders will get deleted to avert any wrong folder deletion. See the example below.

Remove-Item C:\Temp\Test\ -Recurse -Force -WhatIf -Verbose

Output:

PowerShell Delete Folder Example 2

If you have permission to delete the remote folder then you can provide the shared path of the folder there. For example,

Remove-Item '\\Computer1\C$\Temp\Test\' -Recurse -Force -WhatIf -Verbose

The above command will delete the C:\temp\Test folder on the remote computer Computer1.

Example #3

Use Remove-Item as the pipeline. We can retrieve the files and folder content with the Get-ChildItem and Remove-Item to pipeline the output of the first command to remove the folder.

Get-ChildItem C:\Temp\Test\ | Remove-Item -Recurse -Force -Verbose

The problem with this approach is that it deletes the content of the folder but not the folder itself. You need to add more logic to delete but if you want to delete the specific subfolder inside the parent folder then this method is useful that we will see in the example8.

Example #4

Using cmd commands to delete the folder.

  • Using del

When we use the Del command it only deletes the inside files and folders and but leaves the original folder empty.

del c:\Temp\Test\

When you run this command to delete the test folder content, it will prompt for deletion.

command to delete the test folder content

To delete the subfolders, files including read-only, forcefully use the below command.

c:\>del c:\Temp\Test /s /q /f

Output:

To delete the subfolders

  • Use the rmdir to delete the folder instead of the del

rmdir C:\Temp\Test

when you run the above command, you will get the message as below because the directory contains the subfolders and files.

Use the below command to delete the specified folder, subfolders, and files in quiet mode.

c:\>rmdir C:\Temp\Test /s /q

Example #5

Using File System Object method. We can also delete the folder using the ComObject FileSystemObject as shown below.

$obj = New-Object -ComObject Scripting.FileSystemObject
$obj.DeleteFolder("C:\Temp\Test")

Example #6

Using .Net Class method. We can use the .Net class System.IO.Directory  with the Delete() method to delete the folder.

For example:

PS C:\> [System.IO.Directory]::Delete("C:\Temp\Test")

When you run the above command, it throws an exception that the directory is not empty because the above command is meant to delete the empty directory.

Empty Directory Example 6

So to delete the folder, add the second parameter $true for deleting the folder which is not empty.

[System.IO.Directory]::Delete("C:\Temp\Test", $true)

Example #7

Using PowerShell DSC to delete the folder. Using the declarative method DSC to delete the folder.

Configuration FolderDelete{
Node Localhost{
File TestFolderDelete{
DestinationPath = 'C:\Temp\Test'
Type = 'Directory'
Ensure = 'Absent'
Force = $true
}
}
}
FolderDelete -OutputPath C:\Temp\FolderDelete\ -Verbose
Start-DscConfiguration -Path C:\Temp\FolderDelete -Wait -Force -Verbose

Output:

PowerShell Delete Folder Example 7

The above command will store the configuration in C:\temp\FolderDelete,  and make sure that the path exists before you run the script and it will generate the MOF file.

You can also provide the remote nodes in the Node section like

Node @("Computer1","Computer2")

Example #8

Delete the hidden folders using PowerShell. To remove the hidden folders we first need to retrieve the hidden folder using Get-ChildItem.

Get-ChildItem C:\Temp\Test\ -Hidden

Output:

Get-ChildItem Example 8

We will append Remove-Item as a Pipeline to delete that hidden folder.

Get-ChildItem C:\Temp\Test\ -Hidden | Remove-Item -Force -Recurse -Verbose

Output:

PowerShell Delete Folder Example 8

Conclusion

Windows File Explorer is used to interact with the file system files and folders but for the various reasons we need to delete the folder when we write a script or for the regular maintenance of the system we need to delete the folders to free up the extra space, we can use the methods described in this article.

Recommended Articles

This is a guide to PowerShell Delete Folder. Here we discuss a brief overview on the PowerShell Delete Folder, its syntax, methods and its Examples along with Code Implementation. You may also have a look at the following articles to learn more–

  1. PowerShell Loop through Array
  2. PowerShell Dictionary
  3. Powershell Copy File
  4. PowerShell join string

Все способы:

  • Важная информация
  • Способ 1: Приложение «Параметры»
  • Способ 2: Сторонние приложения
  • Способ 3: Апплет «Программы и компоненты»
  • Вопросы и ответы: 0

Важная информация

Существует две ветки развития «PowerShell»: версии с 1.0 до 5.1 и версии 6.0 и выше. Все версии «PowerShell» первой ветки являются глубоко интегрированными в систему, поэтому их удаление не предусматривается, в том числе средствами «Командной строки». Предустановленную версию консоли можно отключить, но при этом она по-прежнему будет присутствовать в образе системы. О способах отключения «PowerShell» в Windows 10 читайте по этой ссылке:

Подробнее: Отключение «PowerShell» в Windows 10

Что касается версий второй ветки, они могут быть удалены как средствами самой Windows 10, так и средствами сторонних программ-деинсталляторов.

Способ 1: Приложение «Параметры»

Это самый простой и очевидный способ. Консоль «PowerShell» версии 6.0 или выше удаляется через соответствующий раздел приложения «Параметры».

  1. Откройте приложение «Параметры» и перейдите в раздел «Приложения»«Приложения и возможности».
  2. Найдите в списке «PowerShell», выделите его мышкой и кликните по «Удалить».

Как удалить «PowerShell» в Windows 10-1

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

Способ 2: Сторонние приложения

Для более тщательного удаления «PowerShell» есть смысл использовать сторонние программы-деинсталляторы, и с некоторыми из них можно ознакомиться по ссылке ниже. В данном примере используется бесплатный деинсталлятор Revo Uninstaller.

Скачать Revo Uninstaller с официального сайта

Подробнее: Программы для удаления программ

  1. Скачайте бесплатную версию приложения с сайта разработчика и установите.
  2. Запустив программу, выберите в списке инсталлированных на компьютере приложений «PowerShell» и нажмите кнопку «Удалить».
  3. Как удалить «PowerShell» в Windows 10-2

  4. В открывшемся окне мастера Revo Uninstaller щелкните по «Продолжить».
    Как удалить «PowerShell» в Windows 10-3

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

  5. Подтвердите удаление в диалоговом окошке.
  6. После того как «PowerShell» будет удален, нажмите кнопку «Сканировать».
  7. Как удалить «PowerShell» в Windows 10-5

  8. В следующем окне кликните на «Выбрать все», а затем — на «Удалить».
  9. Как удалить «PowerShell» в Windows 10-6

  10. Подтвердите действие нажатием кнопки «Да» в диалоговом окне.
  11. Как удалить «PowerShell» в Windows 10-7

Способ 3: Апплет «Программы и компоненты»

В Windows 10 по-прежнему доступен апплет «Программы и компоненты» классической «Панели управления», используйте его для удаления «PowerShell».

  1. Откройте апплет «Программы и компоненты» командой appwiz.cpl, выполненной в диалоговом окошке быстрого запуска приложений. Для его вызова нажмите на клавиатуре комбинацию Win + R.
  2. Как удалить «PowerShell» в Windows 10-8

  3. Найдите в списке установленных программ «PowerShell» и щелкните по «Удалить».
  4. Как удалить «PowerShell» в Windows 10-9

  5. Подтвердите действие нажатием «Да» в диалоговом окошке.
  6. Как удалить «PowerShell» в Windows 10-10

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

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

Skip to content

Powershell — удаление файлов и папок

Powershell — удаление файлов и папок

Хотите узнать, как удалять файлы и папки с помощью Powershell? В этом руководстве мы покажем вам, как удалить папки рекурсивно и файлы с помощью Powershell.

• Windows 2012 R2
• Windows 2016
• Windows 2019
• Windows 2022
• Windows 10
• Окна 11

Список оборудования

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

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

Похожий учебник — PowerShell

На этой странице мы предлагаем быстрый доступ к списку учебников, связанных с PowerShell.

Учебник по Powershell — Удаление файлов

Запустите командную линию Powershell.

Удалите файл с помощью Powershell.

Принудительное удаление файла с помощью Powershell.

Удалите несколько файлов с помощью Powershell.

Удаление всех файлов внутри папки.

Удалите все файлы с одинаковым расширением.

Удаление папки с помощью Powershell.

Поздравляю! Вы можете удалять файлы с помощью Powershell.

Учебник Powershell — Удаление папок

Запустите командную линию Powershell.

Удалите пустую папку с помощью Powershell.

Удалите папку и все ее содержимое с помощью Powershell.

Принудительное удаление папки с помощью Powershell.

Удалите несколько каталогов с помощью Powershell.

Поздравляю! Вы можете удалять папки с помощью Powershell.

VirtualCoin CISSP, PMP, CCNP, MCSE, LPIC22023-04-10T20:12:51-03:00

Related Posts

Page load link

This website uses cookies and third party services.

Ok

Getting rid of any file on Windows 10 is as easy as eating pie. However, the duration of the deletion process executed in File Explorer varies from item to item. The various factors that influence it are size, number of individual files to be deleted, file type, etc. Thus, deleting large folders containing thousands of individual files can take hours. In some cases, the estimated time displayed during deletion can even be more than a single day. Moreover, the traditional way of deleting is also slightly inefficient as you will need to empty Recycle bin to permanently remove these files from your PC. So, in this article, we will discuss how to delete folders and subfolders in Windows PowerShell quickly.

How to Delete Folders and Subfolders in PowerShell

Table of Contents

The simplest ways of deleting a folder are listed below:

  • Select the item and press the Del key on the keyboard.
  • Right-click on the item and select Delete from the context menu that appears.

However, the files that you delete are not permanently deleted by the PC, since the files will still be present in the Recycle bin. Hence, to remove files permanently from your Windows PC,

  • Either press Shift + Delete keys together to delete the item.
  • Or, right-click Recycle bin icon on the Desktop & then, click Empty recycle bin option.

Why Delete Large Files in Windows 10?

Here are some reasons to delete large files in Windows 10:

  • The disk space on your PC might be low, so it is required to clear out space.
  • Your files or folder might have duplicated accidentally
  • Your private or sensitive files can be deleted so that no one else can access these.
  • Your files might be corrupt or full of malware due to attack by malicious programs.

Issues With Deleting Large Files and Folders

Sometimes, when you delete larger files or folders you might face annoying issues like:

  • Files can’t be deleted – This happens when you try to delete application files and folders instead of uninstalling them.
  • Very long duration of deletion – Before starting the actual deleting process, the File Explorer checks the contents of the folder & calculates the total number of files to provide an ETA. Apart from checking and calculating, Windows also analyzes the files in order to display updates on the file/folder that is being deleted at that moment. These additional processes contribute greatly to the overall delete operation period.

Must Read: What is HKEY_LOCAL_MACHINE?

Fortunately, there are a few ways to bypass these unnecessary steps and speed up the process to delete large files from Windows 10. In this article, we will walk you through various methods of doing the same.

Method 1: Delete Folders and Subfolders in Windows PowerShell

Follow the steps mentioned below to delete large folders using PowerShell app:

1. Click on Start and type powershell, then click on Run as administrator.

open Windows PowerShell as administrator from windows search bar

2. Type the following command and hit the Enter key.

Remove-Item -path C:\Users\ACER\Documents\large_folders -recurse

Note: Change the path in the above command to the folder path which you want to delete.

type the command to delete file or folder in Windows PowerShell. How to Delete Folders and Subfolders in PowerShell

Also Read: How to Delete Win Setup Files in Windows 10

Method 2: Delete Folders and Subfolders in Command Prompt

According to official Microsoft documentation, the del command deletes one or more files and the rmdir command deletes file directory. Both of these commands can also be run in the Windows Recovery Environment. Here’s how to delete folders and subfolders in Command Prompt:

1. Press Windows + Q keys to launch the search bar.

Press Windows key and Q to launch the Search bar

2. Type Command Prompt and click the Run as Administrator option in the right pane.

Type Command Prompt and click Run as Administrator option on the right pane. How to Delete Folders and Subfolders in PowerShell

3. Click Yes in the User Account Control pop-up, if prompted.

4. Type cd and the folder path you want to delete and hit Enter key.

For example, cd C:\Users\ACER\Documents\Adobe as shown below.

Note: You can copy the folder path from the File Explorer application so that there are no mistakes.

open a folder in command prompt

5. The command line will now reflect the folder path. Cross-check it once to ensure the entered path to delete the correct files. Then, type the following command and hit Enter key to execute.

del /f/q/s *.* > nul

enter command to delete the folder in command prompt. How to Delete Folders and Subfolders in PowerShell

6. Type cd . . command to go back one step in the folder path and hit Enter key.

type cd.. command in command prompt

7. Type the following command and hit Enter to delete the folder specified.

rmdir /q/s FOLDER_NAME

Change the FOLDER_NAME with the name of the folder which you want to delete.

the rmdir command to delete the folder in command prompt

This is how to delete large folders and subfolders in Command Prompt.

Also Read: How to Force Delete File in Windows 10

Method 3: Add Quick Delete Option in Context Menu

Although, we have learned how to delete folders and subfolders in Windows PowerShell or Command Prompt, the procedure needs to be repeated for every individual large folder. To ease this further, users can create a batch file of the command and then add that command to File Explorer context menu. It is the menu that appears after you right-click on a file/folder. A quick delete option will then be available for every file and folder within the Explorer for you to choose from. This is lengthy procedure, so follow it carefully.

1. Press Windows + Q keys together and type notepad. Then click Open as shown.

search notepad in windows search bar and click open. How to Delete Folders and Subfolders in PowerShell

2. Carefully copy and paste the given lines in the Notepad document, as depicted:

@ECHO OFF
ECHO Delete Folder: %CD%?
PAUSE
SET FOLDER=%CD%
CD /
DEL /F/Q/S "%FOLDER%" > NUL
RMDIR /Q/S "%FOLDER%"
EXIT

type the code in Notepad

3. Click the File option from the top left corner and choose Save As… from the menu.

click on File and select Save as option in Notepad. How to Delete Folders and Subfolders in PowerShell

4. Type quick_delete.bat as File name: and click the Save button.

Type quick delete.bat to the left of File name and click Save button.

5. Go to Folder location. Right-click quick_delete.bat file and choose Copy shown highlighted.

Right click quick delete.bat file and choose Copy from the menu. How to Delete Folders and Subfolders in PowerShell

6. Go to C:\Windows in File Explorer. Press Ctrl + V keys to paste the quick_delete.bat file here.

Note: In order to add the quick delete option, the quick_delete.bat file needs to be in a folder that has a PATH environment variable of its own. The path variable for the Windows folder is %windir%.

Go to Windows folder in File Explorer. Press Ctrl and v to paste the quick delete.bat file in that location

 

7. Press Windows + R keys simultaneously to launch Run dialog box.

8. Type regedit and hit Enter to open the Registry Editor.

Note: If you are not logged in from an administrator account, you will receive a User Account Control pop-up requesting permission. Click on Yes to grant it and continue the next steps to delete folders and subfolders.

type regedit in Run dialog box

9. Go to HKEY_CLASSES_ROOT\Directory\shell as depicted below.

go to the shell folder in registry editor. How to Delete Folders and Subfolders in PowerShell

10. Right-click on shell folder. Click New> Key in the context menu. Rename this new key as Quick Delete.

right click on shell folder and click New and select Key option in Registry Editor

11. Right-click on the Quick Delete key, go to New, and choose Key from the menu, as illustrated below.

right click on Quick Delete and select New and then Key option in Registry Editor

12. Rename the new key as Command.

rename the new key as command in Quick Delete folder in Registry Editor

13. On the right pane, double-click on the (Default) file to open the Edit String window.

double click on Default and Edit String window will pop up. How to Delete Folders and Subfolders in PowerShell

14. Type cmd /c “cd %1 && quick_delete.bat” under Value Data: and click OK

enter the value data in Edit String window in Registry Editor

The quick Delete option has now been added to the Explorer context menu.

15. Close the Registry Editor application and go back to the Folder you wish to delete.

16. Right-click on the folder and choose Quick Delete from the context menu, as shown.

Close the Registry Editor application and go back to the folder you wish to delete. Right click on the folder and choose Quick Delete. How to Delete Folders and Subfolders in PowerShell

As soon as you select Quick Delete, a command prompt window will appear requesting confirmation of the action.

17. Cross-check the Folder path and the Folder name once and click any key on the keyboard to delete the folder quickly.

Note: However, if you accidentally selected the wrong folder and would like to terminate the process, press Ctrl + C. The command prompt will again ask for confirmation by displaying the message Terminate batch job (Y/N)? Press Y and then hit Enter to cancel the Quick Delete operation, as depicted below.

terminate batch job to delete folder in command prompt

Also Read: How to Delete Broken Entries in Windows Registry

Pro Tip: Table of Parameters & their Uses

Parameter Function/Use
/f Forcefully deletes read-only files
/q Enables quiet mode, you do not need to confirm for every deletion
/s Executes the command on all files in folders of the specified path
*.* Deletes all the files in that folder
nul Speeds up the process by disabling console output

Execute del /? command to learn more on the same.

Execute del To know more information on the del command

Recommended:

  • Where Does Microsoft Store Install Games?
  • How to Fix PDFs Not Opening in Chrome
  • How to Disable Google Software Reporter Tool
  • How to Add Notepad++ Plugin on Windows 10

The above methods are the most effective methods to delete large folders in Windows 10. We hope that this guide helped you to learn how to delete folders and subfolders in PowerShell & Command Prompt. Also, if you have any queries/comments regarding this article, feel free to drop them in the comments section.

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

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • В windows 7 не идет время
  • Как установить приложения на андроид на windows phone
  • Как попасть в папку appdata windows 10
  • End of life windows server 2016
  • Windows 11 не работает перетаскивание в панель задач