How to Recursively Delete Entire Directory

Introduction

PowerShell is a powerful scripting tool used to automate tasks on Windows operating systems. It can be used to quickly and efficiently delete entire directories, or folders, and all their contents.

In this blog post, we will discuss the basics of how to use PowerShell scripts to recursively delete an entire directory and its content.

Solution

Recursively deleting an entire directory consists of two steps: first, you must locate the directory you wish to delete; second, you must use specific command (cmdlet) to do the deletion.

Using Remove-Item Cmdlet

In this context, we delete directory C:\Scripts\ and all its contents. We use switch parameter Recurse to recursively delete the directory and its contents. We also use Force switch parameter to force deleting the directory.


Remove-Item -Recurse -Force -Path 'C:\Scripts\'

We can also use the alias of Remove-Item cmdlet which is rm. It looks the same with Unix rm command.


rm -r -fo 'C:\Scripts\'

There are some other aliases which can be checked using Get-Help Remove-Item command.

Get Remove Item Command Aliases

In case there is an error if the directory does not exist, we can use optional parameter ErrorAction to silently continue the execution.


Remove-Item -Recurse -Force -Path 'C:\Scripts\' -ErrorAction SilentlyContinue

Using .Net Objects

Since PowerShell supports .Net Objects, we can also use its libraries to perform the deletion.


$obj = New-Object -ComObject scripting.filesystemobject
$obj.DeleteFolder("C:\Scripts")

Conclusion

Using PowerShell scripts is an easy way to quickly delete entire directories from your computer. With just a few simple commands, such as Remove-Item followed by some switches such as -Recurse and –Force, it is possible to recursively delete an entire directory with all its contents without any hassle or worry about permissions issues. Besides that, we can also use .Net objects.