---
title: "Efficient File Deletion with PowerShell: Remove-Item and WMI"
description: "Save time and effort by using PowerShell to delete files, including files older than a specific date, with Remove-Item and WMI."
canonical: "https://adamtheautomator.com/powershell-to-delete-files/"
---

# Efficient File Deletion with PowerShell: Remove-Item and WMI

> Save time and effort by using PowerShell to delete files, including files older than a specific date, with Remove-Item and WMI.

Source: https://adamtheautomator.com/powershell-to-delete-files/

---

ATA Learning

Tap to hide

[

ATA Learning

](/)

*   [Home](/)
*   [Tutorials](/tutorials/)
*   [Instructors](/author/)
*   [Advertising](/advertising/)
*   [Recommended Resources](/resources/)
*   [About Adam](/about-adam/)

Search for:  

*   [](https://twitter.com/adbertram)
*   [](https://github.com/Adam-the-Automator)
*   [](https://www.linkedin.com/company/adam-the-automator-llc)
*   [](/feed/)

![Efficient File Deletion with PowerShell: Remove-Item and WMI](https://adamtheautomator.com/wp-content/uploads/2020/03/lukasz-juszczak-MUpe69mjUpg-unsplash.jpg)

# Efficient File Deletion with PowerShell: Remove-Item and WMI

[![](https://secure.gravatar.com/avatar/9a14f10ff1b1ec7d790d34f5b559e4d3de2d31b172e6ef266dfd8b479174d97b?s=192&d=mm&r=g)June Castillote](https://adamtheautomator.com/author/june/)29 January 202110 min. read

Categories: [IT Ops](/category/it-ops/)

Tags:[PowerShell](/tag/powershell/)

Table of Contents

*   [Prerequisites](#prerequisites)
*   [Using the Remove-Item Cmdlet to Delete Files](#get-childitem-and-remove-item-the-powershell-way-to-delete-files)
*   [Using PowerShell to Delete a File](#example-1-using-powershell-to-delete-a-file)
*   [Using PowerShell to Delete All Files in Folder](#example-2-using-powershell-to-delete-all-files-in-folder)
*   [Using PowerShell to Delete All Files Recursively](#example-3-using-powershell-to-delete-all-files-recursively-and-dealing-with-the-long-path-problem)
*   [Working Around the Long Path Problem](#h-working-around-the-long-path-problem)
*   [Using PowerShell to Delete Files Older Than x Days](#example-4-using-powershell-to-delete-files-older-than-x-days)
*   [Using PowerShell to Match and Delete File Patterns](#example-5-using-powershell-to-delete-selected-files)
*   [Deleting Files using WMI in PowerShell](#get-ciminstance-and-invoke-cimmethod-deleting-files-using-wmi-in-powershell)
*   [Using PowerShell and WMI to Delete a File](#example-1-using-powershell-to-delete-a-file-wmi-)
*   [Using PowerShell and WMI to Delete All Files in Folder](#example-2-using-powershell-to-delete-all-files-in-folder-wmi-)
*   [Using PowerShell and WMI to Delete Files By Extension](#example-3-using-powershell-to-delete-files-by-extension-wmi-)
*   [Comparing WMI and Remove-Item](#h-comparing-wmi-and-remove-item)
*   [Next Steps](#conclusion)
*   [Further Reading](#further-reading)

Maintaining free disk space is crucial when managing servers and systems. As admins, you wouldn’t want to get caught unaware of a ‘disk full’ situation. To ensure you’re in the clear, you should learn how to use PowerShell to delete files!

Not a reader? Watch this related video tutorial!

**_Not seeing the video? Make sure your ad blocker is disabled._**

In this article, you will learn just about every way you to remove files from your systems with PowerShell.

Let’s start started!

## Prerequisites

This article presents examples using PowerShell, and if you plan to follow along, you will need the following.

*   A computer that is running Windows 10 or above.
*   Windows PowerShell 5.1 or PowerShell 7.0
*   A script editor such as [_Visual Studio Code_](https://code.visualstudio.com/), _[Atom](https://github.blog/2022-06-08-sunsetting-atom/),_ or _[Notepad++](https://notepad-plus-plus.org/downloads/)_.

## Using the Remove-Item Cmdlet to Delete Files

When you simply need to use PowerShell to delete a file, you’ll probably immediately learn about the [`Remove-Item`](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/remove-item?view=powershell-7.3) cmdlet. This cmdlet is the de facto standard for removing files with PowerShell.

Using `Remove-Item` combined with the `Get-ChildItem` cmdlet to read files and folders and the powerful PowerShell pipeline can really make things a breeze.

**_Related: [Get-ChildItem: Listing Files, Registry, Certificates and More](https://adamtheautomator.com/get-childitem/)_**

> _Did you know that the `Remove-Item` cmdlet has an alias by the name of `del`? When working in PowerShell, using `Remove-Item` or `del` will run the same command._

### Using PowerShell to Delete a File

The first example that would be most useful is the most basic – that is, deleting a single file. To delete just a single file, you only need to use the command below. The code below deletes the file _C:\\temp\\random.txt_.

```powershell
Remove-Item -Path C:\temp\random.txt
```

Running the code above in PowerShell would not show anything on the screen unless an error was encountered.

### Using PowerShell to Delete All Files in Folder

In this example, the code below deletes all files in a folder. The `Get-ChildItem` cmdlet targets  _C:\\temp_ with the `-Path` parameter. The `-File` parameter indicates that the only type of item to be included are _files._ `Get-ChildItem` ignores folders.

```powershell
Get-ChildItem -Path C:\temp -File | Remove-Item -Verbose
```

The output should look like this screenshot below.

![Successfully deleted all files in a folder](https://adamtheautomator.com/wp-content/uploads/2020/05/Untitled-2020-05-27T134034.443.png)

Successfully deleted all files in a folder

### Using PowerShell to Delete All Files Recursively

The previous example only deleted files in the _C:\\temp_ folder. If you need to also delete the files inside every sub-directory, you need to add the `-Recurse` switch to the `Get-ChildItem` cmdlet to get all files recursively.

```powershell
Get-ChildItem -Path C:\temp -File -Recurse | Remove-Item -Verbose
```

Running the above code forces PowerShell to look into all sub-folders and retrieve all the list of files. The output below shows that the code was able to delete files in the top folder; however, it failed to retrieve the files in the sub-folders.

![Failed to retrieve files in sub-folders](https://adamtheautomator.com/wp-content/uploads/2020/05/Untitled-2020-05-27T134046.734-1024x384.png)

Failed to retrieve files in sub-folders

### Working Around the Long Path Problem

The error shown above indicates that the PowerShell _“could not find a part of the path”._ That error is indicative that the path the cmdlet is trying to get to does not exist – which is misleading.

In this case, the error was because the path that the `Get-ChildItem` is trying to read exceeds the _[maximum path length](https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file#maximum-path-length-limitation)_ of 260 characters.

The screenshot below shows that the path or directory and its sub-directories exist and one text file named _InTooDeep.txt_ is located in the bottom-most sub-directory. The combination of all the characters that make up the nested directory names creates a long path problem.

![Nested directories creating a long path name](https://adamtheautomator.com/wp-content/uploads/2020/05/Untitled-2020-05-27T134055.645.png)

Nested directories creating a long path name

In Windows PowerShell 5.1, there is a workaround to the long path name problem. The workaround is to use the Unicode version of the path. Instead of specifying the path like this – _C:\\temp_, use the Unicode version like this – ‘_\\\\?\\C:\\temp’_ for folders located locally, or ‘_\\\\?\\UNC\\<computername>\\<share>\\Temp’_ if the folder is located in a UNC path.

```powershell
Get-ChildItem -Path '\\?\C:\temp' -File -Recurse | Remove-Item -Verbose
```

Using the modified code above that caters to the long path name, the output below shows that PowerShell read the deeply nested path name successfully and deleted the file.

![Deleted the file with a long path name](https://adamtheautomator.com/wp-content/uploads/2020/05/Untitled-2020-05-27T134104.671-1024x277.png)

Deleted the file with a long path name

> _Note that the long path name problem does not affect PowerShell 7.0. With PowerShell 7.0, there is no need to use the Unicode version of the path because it already has built-in support for long path names._

If the folders need to be deleted, too, just remove the `-File` parameter from the `Get-ChildItem` cmdlet, and PowerShell should delete all items, including files and folders.

### Using PowerShell to Delete Files Older Than _x_ Days

Another typical example of disk space housekeeping is deleting files that are older than a specific number of days. This example is useful for removing old log files, like those generated by IIS web servers, to free up disk space.

In this example, there are files in c:\\temp that are older than 14 days. Using the script below, the `Name`, `CreationTIme`, and `AgeInDays` of each file in _c:\\temp_ is shown.

```powershell
Get-ChildItem c:\temp | Select-Object Name,CreationTime,@{n='AgeInDays';e={(New-TimeSpan -Start $PSItem.CreationTime).Days}}
```

As you can see in the screenshot below, there are files that are 15 days old, 7 days old, and 0 days old.

![List of files in c:\\temp](https://adamtheautomator.com/wp-content/uploads/2020/05/Untitled-2020-05-27T134113.151.png)

List of files in c:\\temp

Now that you know the files to remove, you can create a script to only delete files that are older than a specific number of days – in this case, older than 14 days.

In this example script below, files in _C:\\temp_ whose `CreationTime` value is older than the set threshold will be deleted.

The first line defines the path for `Get-ChildItem` to search. The path is saved in the `$path` variable. Then, the second line is where the threshold is specified. The value of the `$threshold` the age in days that the file to be deleted must be.

The next line of code after the `$threshold` variable will:

*   Get the collection of files located in the folder specified in the `$path` variable. In this example, the path is _C:\\temp._
*   Filter the output to include only files whose `CreationTime` value is older than the number of days saved in the `$threshold` variable. In this example, the threshold is 14 days.
*   Pipe the filtered list of files to the `Remove-Item` value to perform deletion of those files.

```powershell
$path = 'C:\Temp'
$threshold = 14
Get-ChildItem -Path $path -File | Where-Object {$PSItem.CreationTime -lt (Get-Date).AddDays(-$threshold)} |Remove-Item -Verbose
```

When you run the above code you will see output like shown below.

![The script deleted the files older than 14 days](https://adamtheautomator.com/wp-content/uploads/2020/05/Untitled-2020-05-27T134127.161.png)

The script deleted the files older than 14 days

Notice that from the screenshot above, based on the verbose message, the script only deleted five files older than 14 days. To confirm that files newer than 14 days still exist, run the code below to list them again.

```powershell
Get-ChildItem c:\temp | Select-Object Name,CreationTime,@{n='AgeInDays';e={(New-TimeSpan -Start $PSItem.CreationTime).Days}}
```

The result below confirms that `Remove-Item` did not delete the newer files.

![Newer files are left untouched](https://adamtheautomator.com/wp-content/uploads/2020/05/Untitled-2020-05-27T134137.488.png)

Newer files are left untouched

### Using PowerShell to Match and Delete File Patterns

Deleting _all_ files, regardless of name, type, or extension is not always the best approach. Sometimes, you need to explicitly exclude or include certain files in the deletion process.

This next example below shows how to delete the files that match \*_.LOG_ filename. One way of doing it by using the `Remove-Item` cmdlet directly with the use of the `-Include` parameter, as shown below.

```powershell
Remove-Item -Path C:\temp\* -Include *.log
```

Another way is, perhaps, the cautious approach is to use `Get-ChildItem` first to collect the list of files to be deleted. Only when you’re satisfied with the list of files for deletion, you can finally pipe the collection to the `Remove-Item` cmdlet.

For example, the code below gets that \*.LOG files in _c:\\temp._

```powershell
Get-ChildItem -Path C:\temp\* -Include *.log
```

As a result of the code above, `Get-ChildItem` returns a list of files matching the _\*.LOG_ filename.

![Only files matching the \*.log filename is returned](https://adamtheautomator.com/wp-content/uploads/2020/05/Untitled-2020-05-27T134147.382.png)

Only files matching the \*.log filename is returned

But, what if you want to exclude a file that contains the number 5 in its name? You can do so by adding the `-Exclude` parameter like this next code.

```powershell
Get-ChildItem -Path C:\temp\* -Include *.log -Exclude *5*
```

Since you excluded the file with the number 5, the result is now different. Specifically, the file _File\_5.log_ is no longer on the list, as shown below.

![The file File\_5.log was excluded](https://adamtheautomator.com/wp-content/uploads/2020/05/Untitled-2020-05-27T134157.175.png)

The file _File\_5.log_ was excluded

When you’re already satisfied with the collection of files that your code creates, then you can pipe the files collection to the `Remove-Item` cmdlet to finally delete those files.

```powershell
Get-ChildItem -Path C:\temp\* -Include *.log -Exclude *5* | Remove-Item -Verbose
```

After running your final code, you will have achieved your goal of deleting only the files you selected.

![Deleting selected files](https://adamtheautomator.com/wp-content/uploads/2020/05/Untitled-2020-05-27T134206.391.png)

Deleting selected files

## Deleting Files using WMI in PowerShell

Now that you have a good understanding of using the common `Remove-Item` cmdlet to remove files, let’s jump into a more advanced use case; using WMI.

PowerShell comes with support for WMI. And support for WMI means that WMI queries and methods can be called from within PowerShell. Yes, WMI is not just for Visual Basic scripts that admins used in the earlier days of Windows.

Microsoft released WMI-specific CIM cmdlets in PowerShell 3.0. The CIM cmdlets that will be used to delete files are the [`Get-CimInstance`](https://learn.microsoft.com/en-us/powershell/module/cimcmdlets/get-ciminstance?view=powershell-7.3&viewFallbackFrom=powershell-7) and [`Invoke-CimMethod`](https://learn.microsoft.com/en-us/powershell/module/cimcmdlets/invoke-cimmethod?view=powershell-7.3&viewFallbackFrom=powershell-7).

### Using PowerShell and WMI to Delete a File

This example assumes that you know the path of the specific file to delete. The `Get-CimInstance` cmdlet with the [`Cim_DataFile`](https://learn.microsoft.com/en-us/windows/win32/cimwin32prov/cim-datafile) class is used to retrieve the information about the file to delete which is _C:\\Temp\\random.txt_.

```powershell
$file2delete = Get-CimInstance -ClassName Cim_DataFile -Filter "Name = 'C:\Temp\random.txt'"
 $file2delete
```

In the above code, the `-Filter` parameter accepts a _[WQL](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_wql?view=powershell-5.1)_ format query. Using WQL requires that you escape some characters including the backslash. And, since the WQL escape character is also the backslash, resulting in the double-backslash characters – `\\`.

Running the code above produces the result shown in the demonstration below. The information about _C:\\Temp\\random.txt_ is saved to the `$file2delete` variable

![Getting a file using WMI query and PowerShell](/wp-content/uploads/2020/03/psdelete01.gif)

Getting a file using WMI query and PowerShell

Now that the information for the file _C:\\Temp\\random.txt_ is retrieved, the resulting object in the `$file2delete` variable can be piped to the `Invoke-CimMethod` cmdlet. The `Invoke-CimMethod` cmdlet has a parameter called `-Name`, which represents the name of the method of the `Cim_DataFile` class.

```powershell
$file2delete | Invoke-CimMethod -Name Delete
```

As you see in the screenshot below, the `ReturnValue` shows 0, which means that the command was successful.

![File successfully deleted using WMI and PowerShell](https://adamtheautomator.com/wp-content/uploads/2020/05/Untitled-2020-05-27T133903.311.png)

File successfully deleted using WMI and PowerShell

> _To know about the possible ReturnValue codes, please refer to this link – [Delete method of the CIM\_DataFile class](https://learn.microsoft.com/en-us/windows/win32/cimwin32prov/delete-method-in-class-cim-datafile)_

Additionally, the screenshot below shows that after running the `Invoke-CimMethod` `Delete()` method, CIM only removed the _C:\\Temp\\random.txt_ file. It did not remove the other files.

![C:\\Temp\\random.txt file was deleted](https://adamtheautomator.com/wp-content/uploads/2020/05/Untitled-2020-05-27T133911.230-1024x294.png)

_C:\\Temp\\random.txt_ file was deleted

### Using PowerShell and WMI to Delete All Files in Folder

In this next example, show you how to delete all files in a folder using PowerShell and WMI. The same cmdlets used in the previous example, which are `Get-CimInstance` and `Invoke-CimMethod`, will be used. But, this time, the WQL query will retrieve all files in the folder instead of just one specific file.

In this next code, the `Get-CimInstance` cmdlet retrieves all files located in _C:\\temp_. As you can see below, the query filters the `Drive` and `Path` properties of the `Cim_DataFile` class.

```powershell
$file2delete = Get-CimInstance -ClassName Cim_DataFile -Filter "Drive = 'c:' AND Path = '\\temp\\'"
```

Running the code above saves the retrieved information about the files in _C:\\temp_ in the `$file2delete` variable. Viewing the value(s) of the `$file2delete` variable shows the output below.

![List of all folders found in c:\\temp using WMI](https://adamtheautomator.com/wp-content/uploads/2020/05/Untitled-2020-05-27T133919.546.png)

List of all folders found in c:\\temp using WMI

Now, the values stored in the `$file2delete` variable can be piped to the `Invoke-CimMethod` to delete all files in _c:\\temp_.

```powershell
$file2delete | Invoke-CimMethod -Name Delete
```

Remember, the `ReturnValue` code of 0 means successful, and for each file that the delete method was called on will have its own `ReturnValue` code.

![All files in c:\\temp deleted using WMI](https://adamtheautomator.com/wp-content/uploads/2020/05/Untitled-2020-05-27T133928.912.png)

All files in c:\\temp deleted using WMI

### Using PowerShell and WMI to Delete Files By Extension

You’ve seen in the previous example how to delete all files in a folder regardless of extension. However, you can also control which files get deleted based on extension.

You’ll notice in the code below, this time the query has an added condition (`Name LIKE '%.log`). This added condition means that only files that match the _.LOG_ extension is returned. The percent (`%`) sign is a WQL _LIKE_ operator that means _“A string of zero or more characters”._ In programming terms, the `%`is the equivalent of a wildcard, which is the asterisk (`*`) character.

```powershell
$file2delete = Get-CimInstance -ClassName cim_datafile `
-Filter "Drive = 'c:' AND Path = '\\temp\\' AND Name LIKE '%.log'"

$file2delete | Invoke-CimMethod -Name Delete
```

The demonstration below shows that before the code above is executed, there are nine \*_.LOG_ files and only one \*_.TXT_ file. Once the code is done running, the \*_.LOG_ files are deleted and the \*_.TXT_ file is the only file left in the folder.

![Deleting files by extension using WMI](/wp-content/uploads/2020/03/psdelete02.gif)

Deleting files by extension using WMI

## Comparing WMI and Remove-Item

So far in this tutorial, you’ve gotten a broad overview of how to use PowerShell to delete files. You’ve learned about `Remove-Item` and also WMI. Both perform similar functions but much differently.

Which method should you use to delete files; `Remove-Item` or WMI?

**Using a built-in cmdlet in PowerShell like `Get-ChildItem` and `Remove-Item` to retrieve and delete files is much faster than when using WMI.**

The example below shows the comparison when using WMI and the built-in PowerShell cmdlet to get the list of files under the _C:\\windows\\web_ directory and its sub-directories.

```powershell
## List all files in C:\Windows\Web\ recursively using Get-ChildItem
Measure-Command { Get-ChildItem C:\Windows\Web\ -Recurse}

## List all files in C:\Windows\Web\ recursively using Get-CimInstance and WMI Query
Measure-Command { Get-CimInstance -ClassName Cim_DataFile -Filter "Drive = 'c:' AND Path = '\windows\web\%'"}
```

When you run the code above in PowerShell, you’ll see the output similar below.

![Get-ChildItem vs. Get-CimInstance with WMI Query](https://adamtheautomator.com/wp-content/uploads/2020/05/Untitled-2020-05-27T134026.529.png)

Get-ChildItem vs. Get-CimInstance with WMI Query

As you can see from the output shown above, listing the files in _C:\\windows\\web_ almost took _ten times_ longer using `Get-CimInstance` than the time it took for `Get-ChildItem` to complete!

Also, did you notice how the `Get-ChildItem` line is much shorter than `Get-CimInstance`? Not only you get faster execution using `Get-ChildItem`, but you also benefit from a cleaner and shorter code.

## Next Steps

In this article, you’ve seen the two different ways you can use PowerShell to delete files with built-in cmdlets and WMI/CIM.

Know that you should always use the `Get-ChildItem` and `Remove-Item` cmdlet to remove files. These built-in cmdlets are more flexible, easier, and faster to use than when using WMI.

Try to come up with a script that can perform disk space housekeeping for you. Sure some scripts already exist for that purpose; by all means, use them as a reference, but if you’re willing to practice and learn, you should try to create your own.

## Further Reading

*   [**_CIM\_DataFile class_**](https://learn.microsoft.com/en-us/windows/win32/cimwin32prov/cim-datafile)
*   [**_Maximum Path Length Limitation_**](https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file#maximum-path-length-limitation)
*   [**_Should I use CIM or WMI with Windows PowerShell?_**](https://devblogs.microsoft.com/scripting/should-i-use-cim-or-wmi-with-windows-powershell/)

Share this article

[Share on X](https://twitter.com/intent/tweet?url=https%3A%2F%2Fadamtheautomator.com%2Fpowershell-to-delete-files%2F&text=Efficient%20File%20Deletion%20with%20PowerShell%3A%20Remove-Item%20and%20WMI)[Share on Facebook](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fadamtheautomator.com%2Fpowershell-to-delete-files%2F)[Share on LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fadamtheautomator.com%2Fpowershell-to-delete-files%2F)

## Related Posts

![](https://adamtheautomator.com/wp-content/uploads/2026/06/26995-troubleshoot-dns-issues-powershell-codex.webp)

### [Troubleshoot DNS Issues with PowerShell](/troubleshoot-dns-issues-powershell/)

Troubleshoot DNS issues with PowerShell by testing name resolution, DNS client settings, cache entries, and network connectivity in a repeatable workflow.

![](https://adamtheautomator.com/wp-content/uploads/2025/10/image_2025-10-24_095322075.png)

### [Migrating from PowerShell 6 to 7.5: Breaking Changes/New Features](/migrating-powershell-6-to-7-5/)

Migrate from PowerShell Core 6 to 7.5: breaking changes, features, and testing tips.

![](https://adamtheautomator.com/wp-content/uploads/2025/06/featured-image-6.png)

### [How to Add Timeouts to Pester Tests with PowerShell Runspaces](/pester-test-timeout-runspaces/)

Prevent Pester tests from hanging indefinitely using PowerShell runspaces. Learn to handle variable scoping, module loading, TestDrive access, and stream capture challenges with timeout protection.

## Categories

*   [IT Ops](/category/it-ops/)
*   [Cloud](/category/cloud/)
*   [DevOps](/category/devops/)
*   [Home Ops](/category/home-ops/)
*   [Information Security](/category/infosec/)
*   [Software Development](/category/software-development/)

## Site

*   [Home](/)
*   [Tutorials](/tutorials/)
*   [Instructors](/author/)
*   [Advertising](/advertising/)
*   [Recommended Resources](/resources/)
*   [About Adam](/about-adam/)

Copyright 2026© ATA Learning | [Privacy Policy](/privacy/)
