How to Delete Folders or Files with PowerShell [20 Examples]

Photo of author

By Victor Ashiedu

Published

Do you want to delete files and folders with PowerShell, but don’t know how? This article shares two methods and 20 examples.

Option 1: Delete Items with the 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 list all files and folders in the path E:\reports, run the command below:

Get-ChildItem E:\reports

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 E:\reports | 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.

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 remaining part of this section, I will show how to use Delete “Method”.

The syntax of the Delete “Method” is:

Object.Delete()

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

To make it easy to understand the above syntax command here is the original Get-ChildItem command:

Get-ChildItem E:\reports

and the result…

Based on what I have explained so far, in theory, you could use PowerShell Delete Method to delete the folder called “reports” by running the command below:

(Get-ChildItem E:\reports).Delete()

However, the last command 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 E:\reports -Include *.* -Recurse | ForEach  { $_.Delete()}

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

The last command deletes the files in the specified folder and its subfolders. However, it does not delete the folders.

To delete the folders, run the command below:

Get-ChildItem E:\reports | ForEach   { $_.Delete()}

To confirm that E:\reports is now empty, I will run the Get-ChildItem command again.

Get-ChildItem E:\reports

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 E:\reports -Include *.* -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, on the other hand, tells Get-ChildItem to return 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.

As I already mentioned when I introduced this section, PowerShell has a cmdlet called Remove-Item specifically. You can also use this PowerShell Cmdlet to delete a folder or a file.

The next section covers how to use Remove-Item. In my experience, using Remove-Item is better than using Delete() “Method”.

Option 2: Deleted Items with Remove-Item

To delete a file or folder with Remove-Item you still need to use the PowerShell Cmdlet, Get-ChildItem. Then pipe the result to Remove-Item.

You can run Remove-Item without Get-ChildItem. However, from my experience, for most circumstances, it works best to list the item with Get-ChildItem. Then, pipe the output to Remove-Item.

Here is the PowerShell command that will delete the folder…

Get-ChildItem E:\reports -Recurse -Filter "ITGServer2" | Remove-Item -Force -Recurse

After running the above command, the folder is gone!

In my second example, I want to delete the folders and sub-folders in E:\reports. The command below will do the job…

 Get-ChildItem E:\reports -Recurse | ForEach { Remove-Item $_.FullName -Force -Recurse } 

After running the last command, all folders in the specified folder are gone!

Fix Common Errors With Powershell Delete

When you run the Remove-Item PowerShell command to delete a folder or file, it may return some errors. This section covers some of those errors and how to fix them.

I feel that it’s better to discuss solutions to these common errors before we dive into some real-life sysadmin examples of how to use PowerShell to delete folders or files.

How to Fix the “Access Denied” Error

If you run Remove-Item to delete a file or folder and receive an “Access Denied” error message, try the following:

  1. Change the Owner of the file or folder – use the codes below to change the owner of a file or folder to the local administrator

To run this command, open PowerShell as administrator, otherwise, the last command will fail.

$CurrentACL = Get-ACL F:\ITGFiles\Textfiles
$AdminGroup = New-Object System.Security.Principal.NTAccount("Builtin", "Administrators")
$CurrentACL.SetOwner($AdminGroup)
Set-Acl -Path F:\ITGFiles\Textfiles -AclObject $CurrentACL
Change the folder path, F:\ITGFiles\Textfiles to the full path of your file or folder

Once you have changed the owner to the local administrator, try running deleting the file or folder again with PowerShell. If it doesn’t work, try these fixes.

  1. Add the Force parameter to Remove-Item
  2. Try the Delete() Method instead. If you don’t know how to use PowerShell Delete() Method, see How To Use Delete() Method In Powershell To Delete A Folder Or File (link opens in a differnt browser tab) section of this guide.

How to Fix “Cannot be Removed Because it is Not Empty” Error

If you receive “cannot be removed because it is not empty” error when you run the command:

Remove-Item E:\reports -Recurse

Try using Get-ChildItem with the Recurse parameter. Then, pipe it to Remove-Item with the Force and Recurse parameters.

Here is a sample command:

 Get-ChildItem E:\reports -Force -Recurse | Remove-Item -Force -Recurse

Alternatively, you can run Get-ChildItem and specify asterisks behind the last slash in the path. This deletes all the content of the folder.

For example, if I run the command…

Remove-Item E:\reports -Force -Recurse

…and receive “Cannot Be Removed Because It Is Not Empty”, to fix the problem, I’ll first run the command below:

 Get-ChildItem E:\reports\* -Force -Recurse | Remove-Item -Force -Recurse

The last command deletes only the items in E:\reports. Finally, to delete the folder (which is now empty), I will run the command below…

Remove-Item E:\reports -Force -Recurse

How to Fix “Used By Another Process” Error

If you receive Remove-Item returns the error message “because it is being used by another process”, you need to include the Force parameter.

Here is the original that returned the error message…

Get-ChildItem E:\reports\folder-names.txt | Remove-Item

To fix this problem, run the command below for a file:

Get-ChildItem E:\reports\folder-names.txt | Remove-Item -Force -Recurse

The last command successfully deleted the file…

How to Fix “Folder or File Name Too Long” Error

This appears to be a known limitation with PowerShell.

However, to fix this problem, you may use the dir cmd command. Then, pipe the result to the Remove-Item command.

Here is an example…

dir "E:\reports\reports - Copy\reports - Copy\reports - Copy\reports - Copy\reports - Copy\reports - Copy\reports - Copy\reports - Copy" | Remove-Item -Force -Recurse
The dir command is the cmd equivalent of PowerShell’s Get-ChildItem.

How to Fix “Access to the Path is Denied” Error

PowerShell Remove-Item command throws “Access To The Path Is Denied” error message if you try to delete a folder you do not have permission to delete.

The reason you get this error message is that you do not have access to the folder. Before you run the Remove-Item command, run the following commands to grant local administrators access to the folder.

This fix assumes that the account you used to log in is a member of the local Administrators group. Before you run the command below in PowerShell ISE, change the path F:\ITGFiles\Textfiles to the folder path you are trying to delete.
$CurrentACL = Get-ACL F:\ITGFiles\Textfiles
$AccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule("BUILTIN\Administrators","FullControl","Allow")
$CurrentACL.SetAccessRule($AccessRule)
$CurrentACL | Set-Acl F:\ITGFiles\Textfiles

Once you finish running the script above, re-run the Remove-Item command.

More Examples

This last section of the guide covers multiple examples of how to use PowerShell to delete files or folders.

How Delete a Folder or File with PowerShell if it Exists

Since this example has a condition – “if the folder or file exists” – the first path of the command checks if the item exists.

You can use the Test-Path command to check if a folder or file exists. Then, you use the IF conditional statement to remove the folder or file if it exists.

We can combine both commands in the IF statement block…

In this example, I want to delete a folder called ITGServer in the path F:\ITGFiles\Textfiles – if the folder exists.

Here is the command…

IF (Test-Path F:\ITGFiles\Textfiles\ITGServer) {

Remove-Item F:\ITGFiles\Textfiles\ITGServer

}

Else {

Write-Host "The folder F:\ITGFiles\Textfiles\ITGServer does not exist"

}

In this example, this folder exists so it was deleted. However, if we try the command with a file that does not exist, we will receive the message in the Else block of the IF statement.

How to Delete a Folder and its Subfolders

To delete a folder and all subfolders, run the Remove-Item command with the Recurse and Force parameters.

Here is an example…

Remove-Item F:\ITGFiles\Textfiles\ITGServer -Recurse -Force

How to Delete a Folder or File Older than x Days

In this example, since we want to delete files or folders older than x days, the first step is to get the days reference. This is done with the Get-Date command.

However, since we want to delete items older than x days, we have to specify x days as a negative value. For example, to delete all files or folders older than 7 days, get the days reference with the command below:

$DaysRef = (Get-Date).AddDays("-7")

Then, use the Get-ChildItem command to get the LastWriteTime property of the item. The LastWriteTime property records the last date a folder or file was modified.

In addition to the LastWriteTime property, the Get-ChildItem command returns another property called PSIsContainer. The PSIsContainer property differentiates a file from a folder.

If PSIsContainer is true, it means that the item is a folder. On the other hand, if PSIsContainer is false, it means that the item is a file.

Before I introduce the LastWriteTime property, let me first run a Get-ChildItem command and filter by the PSIsContainer property:

Get-ChildItem F:\ITGFiles\Textfiles | Where-Object {$_.PSIsContainer -eq $TRUE}

This command returned a single object called ITG because this is the only folder in the path F:\ITGFiles\Textfiles.

Alternatively, to list only files in the path, run the command below:

Get-ChildItem F:\ITGFiles\Textfiles | Where-Object {$_.PSIsContainer -eq $FALSE}

This time around, because I specified by $_.PSIsContainer -eq $FALSE, PowerShell returns all non-folders.

Now that you understand how to list folders or files in a folder, let’s introduce the LastWriteTime property. As I mentioned earlier, the last date and time the item was modified are recorded in the LastWriteTime property.

These commands include the LastWriteTime property:

Get-ChildItem F:\ITGFiles\Textfiles | Where-Object {$_.PSIsContainer -eq $TRUE -AND $_.LastWriteTime -le $DaysRef}
Get-ChildItem F:\ITGFiles\Textfiles | Where-Object {$_.PSIsContainer -eq $FALSE -AND $_.LastWriteTime -le $DaysRef}

The first command returns all folders that were last modified before the day reference saved in the $DaysRef variable. In this example, the day reference is 7 days.

On the contrary, the second command returns all files modified last x days – where x days equals 7 in this example.

The second and final stage of this example that uses PowerShell to delete folders of files older than x days is to pipe the Where-Object command to Remove-Item.

The script below completes the task of deleting the files and folder…

Get-ChildItem F:\ITGFiles\Textfiles | Where-Object {$_.PSIsContainer -eq $TRUE -AND $_.LastWriteTime -le $DaysRef} | Remove-Item -Recurse -Force
Get-ChildItem F:\ITGFiles\Textfiles | Where-Object {$_.PSIsContainer -eq $FALSE -AND $_.LastWriteTime -le $DaysRef} | Remove-Item -Recurse -Force
If no file or folder meets the LastWriteTime criteria none will be deleted.

How to Delete Only Folder Contents

In this example, I will delete the content of F:\ITGFiles\folder but not the folder itself.

If you want to delete only the contents of a folder but retain the folder, run the Remove-Item command as shown in the example below:

Remove-Item F:\ITGFiles\folder* -Recurse -Force

The trick is to add an asterisk after the last slash at the end of the folder path.

The Recurse parameter deletes all folders and sub-folders in the specified path. In this example, F:\ITGFiles\folder*

How to Avoid Prompting for Confirmation While Deleting Items

The trick to deleting a folder and contents without asking you for confirmation is to add the Force and Confirm:$false parameters to the Remove-Item command.

If I run the command below without adding the Confirm:$false parameter, I will be may to confirm that I want to delete the folder and all its contents.

Remove-Item E:\reports -Recurse -Force

However, if I do not want to receive this confirmation prompt, I will include the Confirm:$false parameter.

Remove-Item E:\reports -Force -Recurse -Confirm:$false

The command should run without asking to confirm the action. Also, note that the parameter that stops the confirmation prompt is Confirm:$false.

If the last command still prompts for confirmation, first run the Get-ChildItem command. Then, pipe the output to the Remove-Item command as shown below:

Get-ChildItem -Path E:\reports | Remove-Item -Force -Recurse -Confirm:$false

Unfortunately, the last command does not delete the parent folder “folder”. To delete the parent folder and all its content, add the -filter parameter to the Get-ChildItem command as shown in this command:

Get-ChildItem -Path E:\reports -Filter "folder" | Remove-Item -Force -Recurse -Confirm:$false

How Delete a Folder or File to Recycle Bin

If you delete a folder or file with the Remove-Item command, it is deleted permanently. In other words, the folder is not moved to the Recycle Bin.

Unfortunately, there is no PowerShell Cmdlet to delete a folder or file to Recycle Bin. I was trying to create a custom function for this task. However, I found an existing function created by a stackoverflow.com contributor.

To make it available to our readers, I uploaded a copy of the function to www.itechguides.com. To download and use the function, follow the steps below:

  1. Click download Remove-ItemToRecycleBin.zip to download the function
  2. Then, unzip the downloaded zip file. When you unzip the file, it will create a folder called Remove-ItemToRecycleBin.
  3. Finally, copy the folder to your Windows 10 PowerShell profile mouldule folder. The folder is located in the path below
C:\Users\<UserName>\Documents\WindowsPowerShell\Modules
<UserName> is your Windows 10 profile name. This is usually located in C:\Users\. However, if it is not in drive C, look at drive D or E.

Once you have copied the module folder your module folder, you can use it like any other PowerShell command. To illustrate how it works, I will delete E:\reports to Recycle Bin.

Now, to use PowerShell to delete the folder, E:\reports to Recycle Bin, I’ll run the command below:

Remove-ItemToRecycleBin -LiteralPath E:\reports

After running the above command, the reports folder will be moved to Recycle Bin.

How to Exclude Files or Folders from Deletion

The Remove-Item command has an Exclude parameter. This parameter is used to exclude a folder or file that you do not wish to delete.

Here is an example. I want to delete all folders in the path, F:\ITGFiles\Textfiles5. However, I do not want to delete folder3.

As you can see from the screenshot above, the folder has both folders and files.

To delete only folders, I have to first use the Get-ChildItem command to list all items in the path. Then, pipe the output to the Where-Object and filter by PSIsContainer property.

Get-ChildItem F:\ITGFiles\Textfiles5 | Where-Object {$_.PSIsContainer -eq $TRUE} | Remove-Item -Recurse -Force -Exclude "folder3"

After running the last command, all folders are deleted but not folder3. Also, you notice that files in F:\ITGFiles\Textfiles5 were not deleted.

The reason only folders were deleted is that within the Where-Object block, I filtered by {$_.PSIsContainer -eq $TRUE}. The PSIsContainer property specifies that an object is a folder.

Moving on, the Remove-Item also has a parameter called “Include”. This parameter performs the opposite action to the “Exclude” parameter.

I can achieve the same result as the last command by replacing “Exclude” with “Include”. However, unlike the previous command, I will now list the folders I want to delete.

Here is a sample command that deletes just “folder1” from F:\ITGFiles\Textfiles5.

Get-ChildItem F:\ITGFiles\Textfiles5 | Where-Object {$_.PSIsContainer -eq $TRUE} | Remove-Item -Recurse -Force -Include "folder1"

After running the previous command, you’ll notice that only “folder1” was deleted.

If you want to delete files instead of folders, change the “$_.PSIsContainer -eq $TRUE” to “$_.PSIsContainer -eq $FALSE”

How to Delete a Folder Even if it is Not Empty

If you want to delete a folder with PowerShell – even if the folder is not empty – include the Force and Recurse parameters. Here is an example.

Remove-Item F:\ITGFiles\Textfiles5 -Recurse -Force

How to Delete Empty Folders Older Than x Days

Follow the steps below to use PowerShell to delete empty folders older than x days…

In this example, I want to delete folders older than 90 days from my Windows 10 profile, C:\Users\VictorA.

  1. Use Get-ChildItems to list only folders in the specified path:
Get-ChildItem -Path C:\Users\VictorA -Directory

The command lists all folders in the specified path. If you remember, in previous commands in this guide, to return folders, we used Where-Object to filter by PSIsContainer property. However, I decide to achieve the same result using the Directory parameter of Get-ChildItem.

  1. Then, pipe the result of the Get-ChildItem command to Where-Object. Within the Where-Object command, add a filter that returns only empty folders. Here is the command…
Get-ChildItem -Path C:\Users\VictorA -Directory | Where-Object { $_.GetFileSystemInfos().Count -eq 0 }
  1. Now, we need to add the path that returns folders in the previous list older than 90 days. This involves two commands.

In the first command, I will use Get-Date to determine the date for the time period. In the example, 90 days ago. To make it easier, I will save the result in a variable called $DaysRef.

$DaysRef = (Get-Date).AddDays("-30")

Then, in the second command, I will include another filter in the Where-Object part of the last command.

Get-ChildItem -Path C:\Users\VictorA -Directory | Where-Object { ($_.GetFileSystemInfos().Count -eq 0) -AND ($_.LastWriteTime -le $DaysRef) }

As you can see, only two empty folders are now returned by the last command. I ran this command on 4th August 2021. As you can see, the LastWriteTime of the two folders is 16/06/2021 16:29.
For US readers, this date is 16th August 2021 (06/16/2021)

This means that the last time the two folders were last modified is more than 90 days from when I ran the command.

  1. Finally, to delete these empty folders older than 90 days, pipe the last command to the Remove-Item PowerShell command.
Get-ChildItem -Path C:\Users\VictorA -Directory | Where-Object { ($_.GetFileSystemInfos().Count -eq 0) -AND ($_.LastWriteTime -le $DaysRef) } | Remove-Item -Force -Recurse

How to Delete User Profile Folder

To delete user profile folder with the commands in this section, you MUST open PowerShell as administrator. Otherwise, you may receive an “access denied” error message

The first step to use PowerShell to delete a user’s profile folder is to determine the path to the user’s folder. PowerShell has an environmental variable that returns the path to the Windows installation directory.

The variable is…

$Env:WinDir

This command returns a path like C:\WINDOWS. Meanwhile, the “Users” folder (that contains all user profile folders) is located at the root of the drive where Windows is installed.

In my example, the “Users” folder is located in drive “C:\WINDOWS”.

However, to return “C:\”, from “C:\WINDOWS”, use the split Method as shown in the command below.

($Env:WinDir).Split("\")

The command returns C: and WINDOWS. The next step is to return C: – this is the first item in the array.

To access this item, include this [0] to the last command as shown below.

(($Env:WinDir).Split("\"))[0]

Now, we have C:\

I mentioned earlier that all user profiles are located in the “Users” folder. From the last command, I will add “\Users” to the return C:\Users

(($Env:WinDir).Split("\"))[0] + "\Users"

Now, we have the full path to the “Users” folder.

In the next command, I will use Get-ChildItem to list all user profile folders in the “Users” folder. However, to avoid errors, I’ll first, save the last command in a variable.

$UsersFolder = (($Env:WinDir).Split("\"))[0] + "\Users"

Now, I can use Get-ChildItem to return all user profile folders in the “Users” folder. Here is the command:

Get-ChildItem $UsersFolder

The final bit will be to pipe the last command to Remove-Item. However, you need to use the Filter parameter to delete only the User profile folder you want to get rid of.

In this example, I want to delete the user profile folder called “victo” and all its subfolders

Here is the final command that uses PowerShell to delete “User” Profile Folder:

Get-ChildItem $UsersFolder -Filter "victo" | Remove-Item -Force -Recurse

After running this command, now if you run the command below, the deleted profile will no longer be listed.

Get-ChildItem $UsersFolder

How to Delete Folder From the Appdata Folder

PowerShell has two environment variables for a logged-on user’s AppData folder.

$env:APPDATA - is the environment variable for the "roaming" appdata folder
$env:LOCALAPPDATA - is the "local" appdata folder

The environment variable you decide to use depends on the location of the folder you want to delete. However, if you’re not sure of the location of the folder you want to delete, you can search both locations.

To achieve this, I will save both environment variables into a variable called $appdatafolders…

$appdatafolders = $env:APPDATA, $env:LOCALAPPDATA

Then, I will use the ForEach loop to check both locations. Here is the code that does this job…

ForEach ($appdata in $appdatafolders) {Get-ChildItem $appdata -Recurse -Filter "testfolder" | Remove-Item -Recurse -Force -ErrorAction silentlycontinue -WhatIf}
I included the WhatIf parameter so PowerShell does not delete the folder. Instead, PowerShell will display the action it was to perform if the WhatIf parameter was not included.

Here is the result of the command in PowerShell. The image on the right of the screenshot is the folder in my AppData folder.

How to Delete Hidden Folders

The Get-ChildItem command has a parameter called “Hidden”. If you want to list hidden folders in a specified folder, include the “Hidden” parameter.

In my screenshot below, I have 3 folders (non or them hidden).

To demonstrate how to use PowerShell to delete hidden folders, I will hide “Textfiles3”. Now, the folder is hidden.

To list the hidden folder, I will run the command below…

Get-ChildItem F:\ITGFiles -Hidden

As expected, the command lists just the hidden folder.

To delete the hidden folder with PowerShell, I will now pipe the last command to the Remove-Item command.

Get-ChildItem F:\ITGFiles -Hidden | Remove-Item -Recurse -Force

To confirm that the folder was deleted, I enabled the show “Hidden items” attribute in File Explorer.

How to Delete Files but Keep Folder Structure

There may be instances where you may want to delete all files in a folder, including its subfolders but retain the folder structure.

To achieve this, you need to run the Get-ChildItem command and specify the “File” parameter. When you use the “File” parameter, Get-ChildItem lists only files in the specified folder.

To demonstrate how this works, I have created a folder structure shown in the screenshot below:

As seen in the screenshot, “folder1” has two subfolders, “folder2” and “folder3”. Furthermore, “folder2” and “folder3” have some files.

To use Get-ChildItem to display only files in the path, F:\ITGFiles\folder1, I will run the command below:

Get-ChildItem -Path F:\ITGFiles\folder1 -File -Recurse

The command displays just files in the two paths, F:\ITGFiles\folder1\folder2 and Directory: F:\ITGFiles\folder1\folder3

Finally, to delete the files but keep the folder structure, pipe the last command to Remove-Item…

Get-ChildItem -Path F:\ITGFiles\folder1 -File -Recurse | Remove-Item -Recurse -Force

The command deletes all the files but leaves the folder structure intact!

How to Delete Registry Key

The command to list and delete a registry key folder is the same command used to delete normal folders.

If you have been reading this guide from the beginning, we have used two commands so far:

Get-ChildItem: used to list items in a specified path
Remove-Item: used to delete the files/folders listed by Get-ChildItem

The only difference, however, is how you access registry key folders.

There are multiple ways to format a registry key for use in the Get-ChildItem and Remove-Item commands. However, for this example, I will use the method below:

"registry::HKEY_CURRENT_USER\Control Panel\Desktop"

In this example, I want to access the registry key folder, “HKEY_CURRENT_USER\Control Panel\Desktop”. As you can see in the command format above, to do this, I added the word “registry”, followed by two colons, “::”

To learn more about how PowerShell works with Windows registry, read our guide – How To Use PowerShell To Read Registry Value.

Moving the example to the next step, to list the items in the above registry key folder, run the command below:

Get-ChildItem "registry::HKEY_CURRENT_USER\Control Panel\Desktop"

The command displays all the subkey folders in the specified registry key folder.

If I want to delete a specified folder, I will run Get-ChildItem first. Then, I will pipe the output to Select-Object

Get-ChildItem -Path "registry::HKEY_CURRENT_USER\Control Panel\Desktop" | Select-Object name

The above command displays the full path to all the subkeys in my original registry key folder:

Then, to delete the subkeys, I will pipe the last command to Remove-Item. However, to delete a specific subkey folder, I will first pipe the last command to Where-Object and filter by the name of the subkey I want to delete:

Get-ChildItem -Path "registry::HKEY_CURRENT_USER\Control Panel\Desktop" | Select-Object name | Where-Object {$_.Name -like "colors"}

The last command now returns only the specified registry subkey folder path.

Finally, to delete this folder subkey with PowerShell, pipe the last command to Remove-Item. Before then, though you have to modify the registry key and pipe it to Get-Item.

To make it easy, I will save the last command in a variable

$RefSubkey = (Get-ChildItem -Path "registry::HKEY_CURRENT_USER\Control Panel\Desktop" | Select-Object name | Where-Object {$_.Name -like "colors"}).Name

Then, format it for Get-Item command

$RegKeyFormatted = "registry::$RefSubkey"

Finally, pipe the formatted key path to Get-Item…

$RegKeyFormatted | Get-Item

Now, we can delete the value by piping the last command to Remove-Item (I included “whatif” parameter because I do NOT want to delete this key)

$RegKeyFormatted | Get-Item | Remove-Item -Force -Recurse -whatif

How to Delete Folder Name Using a Filter

In the course of other examples in this guide, I have shown how to use PowerShell to delete a folder name using the “Like” filter. Also, as already shown in previous examples, this filter can be applied in the Get-ChildItem command or in the Where-Object command.

For example, to delete all files and folders with names like “file” in the path F:\ITGFiles, I can use the command below:

Get-ChildItem F:\ITGFiles -Filter "file" -Recurse
For the filter to work, you may need to use a wildcard. In this example, I use the asterisk wildcard.

I can achieve the same result by piping Get-ChildItem to Where-Object. Then, perform the filtering in Where-Object.

Get-ChildItem F:\ITGFiles -Recurse | Where-Object {$_.Name -like "file"}

The command returns the same result as the last command!

As with other examples in this guide, to delete the folder, pipe the output of any of the two commands to Remove-Item.

How to Delete Folders Larger than a Specified Size

If you want to delete folders larger than a specified size with PowerShell, you have to calculate folder sizes in the specified path first.

However, you have to list the full path to the sub-folders in the specified folder path. To list the full path to all subfolders in a folder path, run a command similar to the one below:

$subfolderpaths = (Get-ChildItem F:\ITGFiles -Depth 0 | Where-Object {$_.PSIsContainer -eq $TRUE}).FullName

The command lists the full paths to all the sub-folders in the folder path, F:\ITGFiles

Using the Depth parameter with a 0 value, instead of Recurse ensures that only the first level sub-folders are returned.

Now that I have the full path to the sub-folder, I will use this information to compute the size of each sub-folder. However, to have the full path to the sub-folders (required to delete it later) and the size, I need to create a custom script.

Here is the full script:

$subfolderpaths = (Get-ChildItem F:\ITGFiles -Depth 0 | where-Object {$_.PSIsContainer -eq $TRUE}).FullName 
#Using Depth 0, instead of Recurse ensures that only the first level folders are returned

         ForEach ($folderpath in $subfolderpaths) {

         $FolderPath = $folderpath

         $FolderSize = [math]::round((Get-ChildItem $folderpath -Recurse  | Measure-Object -Property Length -Sum).Sum /1MB, 1)

         $report = "" | Select-Object -Property FolderPath, "FolderSize (MB)"
         $report.FolderPath = $FolderPath
         $report.'FolderSize (MB)' = $FolderSize

           If ($report.'FolderSize (MB)' -ge 10) {
           $report

}

} 

As you can see from the screenshot, the script returns only one file that meets the size (10 MB) criteria.

Obviously, we have one last bit to complete the task – delete the file. To delete the file that meets the size requirement, I modified the IF statement as shown in this script…

If ($report.'FolderSize (MB)' -ge 10) {

Remove-Item $report.FolderPath -Force -Recurse

}

So, here is the final script that deletes folders larger than a specified value

$subfolderpaths = (Get-ChildItem F:\ITGFiles -Depth 0 | where-Object {$_.PSIsContainer -eq $TRUE}).FullName 
#Using Depth 0, instead of Recurse ensures that only the first level folders are returned

ForEach ($folderpath in $subfolderpaths) {


$FolderPath = $folderpath

$FolderSize = [math]::round((Get-ChildItem $folderpath -Recurse  | Measure-Object -Property Length -Sum).Sum /1MB, 1)

$report = "" | Select-Object -Property FolderPath, "FolderSize (MB)"
$report.FolderPath = $FolderPath
$report.'FolderSize (MB)' = $FolderSize


If ($report.'FolderSize (MB)' -ge 10) {

Remove-Item $report.FolderPath -Force -Recurse

}

} 
To use the script, change the path F:\ITGFiles in the Get-ChildItem – line 1. Also, change the size of the folder you want to delete – from 10 (in MB) to your required size.

How to Delete a Shared Network Folder

The process of using PowerShell to delete network folders is not different from deleting local folders. The only difference is how you specify a network folder.

In addition to the way you specify a network folder, you also need to have the right permissions. Specifically, you need to have “Change” Share permission.

Moreover, you also need to have “Modify” NTFS security permission.

Once these permissions requirements are met, you can access the network folder with the Get-ChildItem command. Then, to delete the folder, pipe the output of Get-ChildItem to Remove-Item.

To demonstrate how to use PowerShell to delete a network folder, I will be using a shared folder called “TestShare”. The folder is located on my Windows 11 test PC called “ITGWIN11BETA”.

To list the content of the shared network folder, I will use the Get-ChildItem command as shown below…

Get-ChildItem \ITGWIN11BETA\TestShare -Recurse

Just like a local folder, the command lists all the folders and subfolders in the shared network folder.

From this point, you can pipe the last command directly to Remove-Item. Alternatively, you apply some filter before piping it to Remove-Item.

For example, if you want to delete a specific folder, you can use the Filter parameter in Get-ChildItem. Alternatively, you can pipe Get-ChildItem to Where-Object and use the Filter parameter in Where-Object.

Finally, to delete the item in the network shared folder, pipe the result to Remove-Item.

How to Delete a Folder or File Starting with a String

If you wish to delete folders or files starting with a particular name, you can use the Filter parameter in Get-ChildItem Cmdlet to list the files. Then, ipe the result to Remove-Item.

Alternatively, you can use the Delete() Method in Get-ChildItem.

As I mentioned earlier, the first step is to use Get-ChildItem Cmdlet with the Filter parameter. Here is a sample command:

Get-ChildItem F:\ITGFiles\Textfiles -Filter *f*
Another option could be to pipe Get-ChildItem to Where-Object and perform the filtering in Where-Object .

The final step to deleting all folders and files starting with f is to pipe the output of

Get-ChildItem F:\ITGFiles\Textfiles -Filter *f* | Remove-Item -Recurse -Force

How to Delete the SoftwareDistribution Folder

As you may already know, the Windows stores downloaded updates in the SoftwareDistribution folder. Ideally, you’ll not need to delete this folder.

However, if the Windows Update database is corrupt, one way to fix it is to delete the SoftwareDistribution folder. Before you do that though, you first need to stop the Windows Update.

To stop the Windows Update service, run PowerShell as administrator. Then, run the command below:

Get-Service -Name wuauserv | Stop-Service
If you do not stop the Windows Update service, you will NOT be able to delete the SoftwareDistribution folder

Next, to use PowerShell to delete the SoftwareDistribution folder run the commands below:

$SoftwareDistribution = $env:SystemDrive + "\Windows\SoftwareDistribution"
Get-ChildItem $SoftwareDistribution -Recurse -force | Remove-Item -Recurse -Force
$Windowsfolder = $env:SystemDrive + "\Windows"
Get-ChildItem $Windowsfolder -filter SoftwareDistribution | Remove-Item -Recurse -Force

Finally, to recreate the SoftwareDistribution folder, restart the Windows Update service

Get-Service -Name wuauserv | Start-Service

How to Delete a File or Folder after Zipping it

To zip a file or folder use the Compress-Archive command as shown in the example below:

Compress-Archive -LiteralPath F:\ITGFiles\Textfiles2 -DestinationPath F:\ITGFiles\Textfiles2 -CompressionLevel Fastest
Change LiteralPath to the source path of the file or folder you want to zip. Also, change DestinationPath to the path you want to save the zipped file.

Once you have zipped the file, use the command below to delete it…

Remove-Item F:\ITGFiles\Textfiles2 -Recurse -Force

How to Delete a File or File, then Write Report to a Log File

If you wish to use PowerShell to delete a file or folder, then report the actions to a log file, you need to first define the log file names.

In this example, I want to have two log files, 1 to log success and the second to log errors.

I normally like to create my log files based on date. For this example, I will first create a date stamp and save it in a variable:

$CurrentDate = Get-Date -Format "dddd-dd-MM-yyyy-HH-mm"

Then, I will create two log files based on the date stamp…

$SuccessLog = "SuccessLog-" + $CurrentDate + ".log"
$ErrorLog = "ErrorLog-" + $CurrentDate + ".log"

There is one missing piece – the directory path to save the log files. To add this bit, I will save the path in a variable…

$Path = "F:\logfiles"

Then, add the path to the log files above…

$SuccessLog = $Path + "\SuccessLog-" + $CurrentDate + ".log"
$ErrorLog = $Path + "\ErrorLog-" + $CurrentDate + ".log"

Now that I have created our log files, I will now create a PowerShell script that will delete files and folders in a specified path. Then, write reports to the log files.

In this example, I want to delete files in the \Windows\Temp folder. The first step is to save the path to this folder in a variable…

$WindowsTemp = $env:SystemDrive + "\Windows\Temp"

Then, I will use Get-ChildItem to list the content of the folder and pipe the output to Remove-Item.

However, to be able to capture the errors, I need to enclose the whole command in a Try, Catch.

Here is the full script…

$error.Clear() #clears all existing errors
Try {
   $CurrentDate = Get-Date -Format "dddd-dd-MM-yyyy-HH-mm"
   $LogPath = "F:\logfiles"
   $SuccessLog = $LogPath + "\SuccessLog-" + $CurrentDate + ".log"
   $ErrorLogFile = $LogPath + "\ErrorLog-" + $CurrentDate + ".log"
   $Path = "E:\reports"
   $items = Get-ChildItem $Path -Recurse -Force -ErrorAction SilentlyContinue 
   ForEach ($item in $items) {
   Remove-Item $item.FullName -Force -Recurse -ErrorAction SilentlyContinue 
   	If (Test-Path $item.FullName -ErrorAction Continue ) {

    #$errormessage = $item.FullName + $error.Exception

	#$error.Exception.Message | Out-File $ErrorLogFile -Append
    $error.ErrorDetails.Message | Out-File $ErrorLogFile -Append
    #Add-Content -Value $error.Exception -Path $ErrorLog

	}
	Else {
    
    #$ItemPath = (Get-Item $item.FullName -ErrorAction SilentlyContinue).FullName

	#"$ItemPath successfully deleted" | Out-File $SuccessLog -Append
    Add-Content -Value "$item successfully deleted" -Path $SuccessLog

	}
   
   
   }

}

Catch {

}
To use the script copy it to PowerShell ISE. Then, change the $Path variable to the path of the folder you want to delete. Also, change the $LogPath to the folder path you want to save your log files.

Conclusion

That is it – our comprehensive guide to use PowerShell to delete files or folders!

I hope you found this guide helpful. If you found it helpful, kindly spare 2 minutes to share your experience by responding to the “Was this page helpful?” question below.

Finally, for more PowerShell guides with examples, visit our Windows PowerShell How-To page. You may also find our FREE PowerShell training guides helpful.

About the Author

Photo of author

Victor Ashiedu

Victor is the founder of InfoPress Media, publishers of Ilifeguides and Itechguides. With 20+ years of experience in IT infrastructure, his expertise spans Windows, Linux, and DevOps. Explore his contributions on Itechguides.com for insightful how-to guides and product reviews.

Related Articles

Get in Touch

We're committed to writing accurate content that informs and educates. To learn more, read our Content Writing Policy, Content Review Policy, Anti-plagiarism Policy, and About Us.

However, if this content does not meet your expectations, kindly reach out to us through one of the following means:

  1. Respond to "Was this page helpful?" above
  2. Leave a comment with the "Leave a Comment" form below
  3. Email us at [email protected] or via the Contact Us page.

2 thoughts on “How to Delete Folders or Files with PowerShell [20 Examples]”

  1. This was all extremely helpful but I need to know how a I can use powershell to delete folders from a list.txt containing the folder names that I want to delete, or ideally use a list.txt and delete any folders that begin with the names in the list and their subfolders and files.
    Can you provide this example please?

    Reply
    • Hi Dale,

      To delete folders listed in a text file, do the following;

      ForEach ($folder in (Get-content filename.txt)) {

      Remove-Item $folder -Recurse -Force

      }

      Note: filename.txt is the file containing the list of your folders

      Reply

Leave a comment