How to Delete Folders or Files in PowerShell

-

|

Introduction

You can delete folders and files in PowerShell using the Delete method or Remove-Item Cmdlet. This guide shows different ways to delete folders and files in PowerShell.

All PowerShell commands and scripts in this guide were tested. So you can copy and reuse them. However, you may need to modify some of them to meet your specific need.

Powershell Delete Folder or File with Delete “Method”

For PowerShell to Delete a Folder you require the Get-ChidItem Cmdlet. Get-ChildItem Cmdlet returns the items and child items in a specified location.

To get the properties of the files and folders in the path C:\PS\DeleteFolder-example\base, run the command below:

Get-ChildItem C:\PS\DeleteFolder-example\base

Here is the result in PowerShell

powershell delete folder or File example
Advertisements


This command has a “Method” called Delete. You can use the Delete “Method” to delete folders and files.

To see available methods in the above command, pipe the command to the Get-Member Cmdlet.

Get-ChildItem C:\PS\DeleteFolder-example\base | Get-Member

The command returned two types of Properties. 1, System.IO.DirectoryInfo (see the first image below). 2, System.IO.FileInfo. The first relates to folders in the path while the second relates to files.

Powershell Delete Folder or File with Delete "Method"

Look closely at the two images. Notice that each of them has a “Method” called Delete. You can use the Delete “Method” in PowerShell to delete a folder or file.

In the next section I will show how to use Delete “Method”

How to Use Delete() Method in Powershell to Delete Folders or Files

The syntax of the Delete “Method” is:

Object.Delete()

Object is the folder of file details returned by the Get-ChidItem Cmdlet
Delete is the “Method” usually followed by () operator.

To make it easy to relate with, here is the original Get-ChildItem command:

Get-ChildItem C:\PS\DeleteFolder-example\base

and the result…

powershell delete folder or File example

Based on what I have explained so far, in theory you could delete the folder called “base” by running the command below:

(Get-ChildItem C:\PS\DeleteFolder-example\base).Delete()

But this returns the error message “The directory is not empty”.

To solve this problem, I need a command that returns all files and folders and sub-folders in the path. Then I need to pipe the result to a ForEach loop.

Here is the modified command:

Get-ChildItem C:\PS\DeleteFolder-example\base -Include *.* -Recurse | ForEach   { $_.Delete()}

Here is the command in PowerShell. All files have been deleted from the path specified.



To confirm that C:\PS\DeleteFolder-example\base is now empty, I will run the Get-ChildItem command again.

Get-ChildItem C:\PS\DeleteFolder-example\base

It doesn’t return anything!

Before I move on to the next section, let me explain how this command deleted all files and sub-folders.

Get-ChildItem C:\PS\DeleteFolder-example\base -Recurse | ForEach   { $_.Delete()}

Get-ChildItem has two parameters called -Include and -Recurse. In the command I used -Include *.* to tell PowerShell to include every file in the result. -Recurse returns all folders and sub-folders.

In the second part of the command, I pipped Get-ChildItem to ForEach statement. ForEach loops through all objects returned by Get-ChildItem and uses the Delete “Method” to delete them.

PowerShell has a cmdlet called Remove-Item specifically for deleting items. The next section covers how to use Remove-Item. In my experience, using Remove-Item is better than using Delete() “Method”.

Powershell Delete Folder or File with Remove-Item Cmdlet

To delete a file or folder with Remove-Item you still need to use Get-ChildItem. Then pipe the result to Remove-Item. In my first example in this section, I want to delete the file called “file with numbers”. See the image below.

Here is the command:

Get-ChildItem "C:\PS\DeleteFolder-example\copy\file with numbers.txt" | Remove-Item -Force

The image below shows the command in PowerShell and the folder showing that the file was successfully deleted.

To delete all files, folders and sub-folders in the path C:\PS\DeleteFolder-example\copy, use the command below:

Get-ChildItem C:\PS\DeleteFolder-example\copy -Recurse | ForEach { Remove-Item $_.FullName -Force -Recurse }

Here is the command and the empty folder:

Powershell Delete Folder or File with Remove-Item Cmdlet
Advertisements


More Powershell Delete Folder or File Examples

In the last section of this guide I will give examples of how to delete files or folders older than a particular date. I will also show how to delete an item if it exists.

Powershell Delete Folder or File If Older than

In this example, I will delete files older than 7 days from the folder shown below:

Deleting files older than a specified date has real-life Windows admin application. A typical use could be to clean up log files. If you have a process that collects log files daily, you may want to automatically delete log files older than x day.

There are 2 date properties of a file or folder: CreationTime and LastWriteTime. See the result below.

CreationTime is the date the file or folder was created or copied
LastWriteTime is the last date the content of the folder or file was last modified.

Here is a Get-ChildItem command that returns the Name, CreationTime and LastWriteTime of all files and folders in the specified path.

You can use one of these properties to delete files based on the last date the file was modified or created.

Before I add the command that will delete the file, lets add the condition that returns only files last modified 7 days ago.

First, here is the command for my date reference:

(Get-Date).AddDays("-7")

And here is the command that will return only files last modified 7 days ago

Get-ChildItem C:\PS\DeleteFolder-example\base | Where-Object { ($_.PSIsContainer -ne $TRUE) -and ($_.LastWriteTime -le (Get-Date).AddDays("-7") ) }

As you can see from the result below, the command returned just files (folders not included – see the reason beneath this image). The files returned also have LastWriteTime less than or equal to (le) 7 days ago.

In the last command:

$_.PSIsContainer -ne $TRUE tells PowerShell to return only files, NOT folders. PSIsContainer defines directories (folders). -ne means NOT Equal to.

$_.LastWriteTime and Get-Date have been explained earlier.

To read more about PowerShell Where-Object command click Powershell Where (Where-Object) Cmdlet: Syntax, Alias, Examples (opens in a new browser tab).

Finally, I will pipe the result of the last command to Remove-Item, via ForEach statement.

Get-ChildItem C:\PS\DeleteFolder-example\base | Where-Object { ($_.PSIsContainer -ne $TRUE) -and ($_.LastWriteTime -le (Get-Date).AddDays("-7") ) } | ForEach { Remove-Item $_.FullName -Force -Recurse }

Here is the command in PowerShell and the folder showing that the files were deleted.

Powershell Delete Folder or File If Older than...
Important Notes
1, the last command did not delete files in the sub-folders because I did not include -Recurse in Get-ChildItem
2, the file called “empty” was not deleted because it did not meet the condition.

Powershell Delete Folder or File If it Exists

In this example, I will show how to delete folders or files if it exists.

The command required is similar to all the commands we have used so far. The only difference is that I will introduce the Test-Path Cmdlet. Test-Path is used to check if a file or folder exist.

For this example, I will also add an IF statement within the ForEach block. The IF statement will be used to test IF the item exists before it is deleted.

In the real world admin situation, this may be useful if you are looking to delete specific files or folders but you want to check if they exist before you delete them.

Following on from the last example, I will delete the remaining folders and files in C:\PS\DeleteFolder-example\base. But only if they exist.

Here is the script.

$items = Get-ChildItem C:\PS\DeleteFolder-example\base | Select-Object -ExpandProperty FullName
ForEach ($item in $items) {
$exisits = Test-Path $item
If ($exisits ) {
Remove-Item $item -Force -Recurse
}
}

And here is the script in PowerShell ISE. The second image confirms that all items were deleted.

I will explain each part of the script using the line numbers in the first image (PowerShell ISE):

line 1:

$items = Get-ChildItem C:\PS\DeleteFolder-example\base | Select-Object -ExpandProperty FullName

Get-ChildItem is piped to Select-Object -ExpandProperty FullName. This returns just the path of each item returned by Get-ChildItem. However, to make it easy for me to manipulate the items in the subsequent commands, I saved the result in a variable called $items.

line 3:

opens the ForEach statement block.

line 4:

$exisits = Test-Path $item

I used Test-Path to check if the file or folder exists before I send it into the IF statement block

In a real-life script, you may want to add error management using a Try Catch statement.

line 5:

opens the IF block.

line 6:

Remove-Item deletes the item

line 7: closes the IF block

line 8:

closes the ForEach statement block

Advertisements


Conclusion

Using PowerShell to delete folders and files is a very useful scripting skills for every serious Admin. However, I strongly recommend using this with caution as any mistake may have serious consequences.

I hope you found this guide helpful!

If you have any questions, use the “Leave a Reply” form at the end of this page. Alternatively, you could share your experience scripting Powershell delete folder or files.

Other Helpful Guides

  1. 18 Most Useful Powershell Commands for Windows Admins
  2. PowerShell ExecutionPolicy Explained

Additional Resources and References

  1. Remove-Item
  2. Get-ChildItem
  • Was this post Helpful?
  • YesNo

LEAVE A REPLY

Please enter your comment!
Please enter your name here

FEATURED POSTS

How to Add Bullet Points in Google Slides

How to Add Bullet Points in Google Slides (Android or iOS Apps or PC)

This Itechguide teaches you how to add bullet points in Google Slides. The guide offers steps to add bullet points in Google...
How to Create a Business Facebook Page without a Personal Account

How to Create a Business Facebook Page without a Personal Account

This Itechguide teaches how to create a business Facebook page without a personal account. There could be a...
How to Wrap Text in Google Sheets

How to Wrap Text in Google Sheets (from a PC or the Apps)

This Itechguide teaches you how to wrap text in Google Sheets. The guide offers steps to wrap text in Google Sheets from...
How to Change Birthday on Facebook

How to Change Birthday on Facebook (from the App or PC)

This Itechguide teaches you how to change birthday on Facebook. The guide contains steps to change birthday on Facebook from the Facebook...
Best Thrillers on Netflix

The 10 Best Thrillers on Netflix

The thrillers on Netflix is quite a large number of movies. Knowing the best thrillers to watch can be a challenge.

ADVERTISEMENTS

TRENDING POSTS

Remote Desktop Connection

Remote Desktop Connection an Internal Error Has Occurred [Fixed]

Introduction I recently received the error message "Remote Desktop Connection an Internal Error Has Occurred". It was strange because...

Find My Samsung: Register and Use Samsung Find my Mobile

Introduction Ever wondered how you could find your Samsung phone if you lost it? Find my Samsung or Samsung...
What is the Difference Between PowerShell and CMD?

Windows Powershell vs CMD: Differences and Similarities

Introduction This short guide compares Windows PowerShell vs CMD (Windows command prompt). I will cover the history and nature...
Spotify No Longer Supports this Version of Microsoft Edge

Spotify No Longer Supports this Version of Microsoft Edge [Fixed]

Introduction When you open Spotify web player on Microsoft Edge, you may receive the error message "Spotify No Longer...
Windows 10 Won't Boot

Windows 10 Won’t Boot With Black Screen? 3 Ways to Fix It

Why Won't Windows 10 Boot Up? If your Windows 10 stops with a black screen, the first question in...

BEST OF ITECHGUIDES

Routing and Remote Access in Windows Server 2016 (Part 2): Configure NAT

Introduction This is part 2 of a 4-part "Routing and Remote Access in Windows Server 2016" series. This part...
Best War Movies on Netflix

The 10 Best War Movies to Watch on Netflix

There are several war movies on Netflix and it is certain that an excellent war film is always a thriller.
How to Copy and Paste on Facebook

How to Copy and Paste on Facebook (from the Mobile App or PC)

This Itechguide teaches you how to copy and paste on Facebook. The guide offers steps to copy and paste on Facebook from...

Our Top 10 PS4 Adventure Games

Are you ready to dive into the fantasy world of PS4 adventure games? You are at the right place.
Gmail Mark All as Read: How to Mark all Emails as Read on Gmail

How to Mark all Emails as Read on Gmail

Introduction If you receive a lot of emails that you do not wish to read, you may want to...

ADVERTISEMENTS

RECENT POSTS

How to Logout of Amazon App

How to Logout of Amazon App (from Android, iPhone or Windows 10)

This Itechguide teaches you how to logout of Amazon app. The guide offers steps to logout of Amazon app for Android, for...
How to Turn off YouTube Notifications

How to Turn off YouTube Notifications (PC or YouTube Apps)

This Itechguide teaches you how to turn off YouTube notifications. The guide offers steps to turn off YouTube notifications from a PC...
How to Change YouTube Thumbnail

How to Change YouTube Thumbnail (PC or YouTube Studio App)

This Itechguide teaches you how to change YouTube thumbnail. The guide offers steps to change YouTube thumbnail from a PC or...
How to Add Bullet Points in Google Slides

How to Add Bullet Points in Google Slides (Android or iOS Apps or PC)

This Itechguide teaches you how to add bullet points in Google Slides. The guide offers steps to add bullet points in Google...
How to Change Shipping Address on Amazon

How to Change Shipping Address on Amazon

This Itechguide teaches you how to change shipping address on Amazon. The guide offers steps to change shipping address on Amazon:

MUST READ

How to Make a Line Graph in Google Sheets

How to Make a Line Graph in Google Sheets

Introduction You can represent your data visually using a line graph in Google Sheets. This guide demonstrates how to...
FTP and SFTP ports

FTP and FTP Port, SFTP and SFTP Port: Quick Reference

Introduction FTP and SFTP are two protocols for transferring files between a server and a client computer. FTP port...
dropbox login

Dropbox Login: Your Ultimate Guide to Dropbox

Introduction Dropbox login allows you to sign in to and use Dropbox. But what is Dropbox? Let's kick off...
How to Set Google Chrome as Default Browser for Windows 10

How to Set Google Chrome as Default Browser for Windows 10

Introduction This guide demos how to set Chrome as default browser for Windows 10. Windows 10 sets Microsoft Edge...
spotify web player not working

Spotify Web Player Not Working [Fixed]

Introduction Spotify Web Player may stop working for you with the following error messages: "Spotify Web Player an Error...

LATEST DEALS

Exclusive Student Offer_Save 10% on selected Surface devices

By using this website you agree to accept our Privacy Policy and Terms & Conditions