Using PowerShell to Delete Files with Remove


The Best WordPress plugins!

1. WP Reset

2. WP 301 Redirects

3. WP Force SSL

PowerShell is a scripting language and command-line environment that’s used to automate system administration tasks on Windows operating systems. It provides a great combination of power, automation, and flexibility in one package. In this article we’ll walk through how to use PowerShell to delete files with the Remove-Item cmdlet using wildcard characters such as -*.jpg or *.bmp.,

The “powershell script to delete files older than 30 days” is a command-line tool that allows users to clear out files on the computer. The command can be used through PowerShell, which is an open-source scripting language.

Using PowerShell to Delete Files with Remove

When it comes to managing servers and systems, having enough free storage space is critical. You don’t want to be caught off guard by a ‘disk full’ scenario as an administrator. You should understand how to remove files using PowerShell to make sure you’re safe!

In this tutorial, you’ll learn how to delete files from your systems using PowerShell in a variety of ways.

Let’s get this party started!


If you want to follow along with this article’s PowerShell examples, you’ll need the following.

Delete Files using the Remove-Item cmdlet

When you only need to remove a file using PowerShell, you’ll probably learn about the Remove-Item cmdlet right away. This cmdlet is the de facto standard in PowerShell for deleting files.

Using Remove-Item in conjunction with Get-ChildItem to read files and directories, as well as the strong PowerShell pipeline, can make things a breeze.

Get-ChildItem (Listing Files, Registry, Certificates, and More) is related to Get-ChildItem (Listing Files, Registry, Certificates, and More).

Did you know there’s an alias for the Remove-Item cmdlet called del? Using Remove-Item or del in PowerShell will execute the same operation.

Delete a File using PowerShell

The most simple example, removing a single file, is the first one that comes to mind. You simply need to execute the command below to remove a single file. The following code removes the file C:temprandom.txt.

Remove-Item -Path C:temprandom.txt Remove-Item -Path C:temprandom.txt Remove-Item -P

If the code above was run in PowerShell, nothing would appear on the screen until an error occurred.

Delete All Files in a Folder Using PowerShell

The code below deletes all files in a folder in this example. With the -Path argument, the Get-ChildItem cmdlet targets C:temp. The -File argument specifies that files are the only kind of item to be included. Folders are ignored by Get-ChildItem.

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

The final product should like the image below.

All files in a folder were successfully removed.All files in a folder were successfully removed.

Using PowerShell to Recursively Delete All Files

Only files in the C:temp folder were destroyed in the preceding example. Add the -Recurse option to the Acquire-ChildItem cmdlet to get all items recursively if you need to remove files within every subdirectory.

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

When you run the preceding code, PowerShell searches all subfolders and retrieves the whole list of files. The code was able to remove files in the top folder, but it was unable to recover files in the subfolders, as seen in the output below.

Files in sub-folders could not be retrieved.Files in sub-folders could not be retrieved.

Getting Around the Problem of the Long Path

PowerShell “could not discover a section of the route,” according to the error message. That error indicates that the route to which the cmdlet is attempting to go does not exist, which is deceptive.

The error occurred because the route that Get-ChildItem was attempting to read was longer than the allowable path length of 260 characters.

The path or directory and its sub-directories are shown in the picture below, with one text file entitled InTooDeep.txt situated in the bottom-most sub-directory. A lengthy path issue is caused by the combination of all the characters that make up the nested directory names.

A lengthy path name is created by nested directories.A lengthy path name is created by nested directories.

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.

Remove-Item -Verbose | Get-ChildItem -Path ‘?C:temp’ -File -Recurse | Get-ChildItem -Path ‘?C:temp’ -File -Recurse

The result below indicates that PowerShell successfully read the deeply nested path name and removed the file using the updated code above that caters to the extended path name.

The file with a lengthy path name was deleted.The file with a lengthy path name was deleted.

PowerShell 7.0 is not affected by the lengthy path name issue. Because PowerShell 7.0 already includes built-in support for lengthy path names, there is no need to utilize the Unicode version of the path.

If you want to destroy the folders as well, just remove the -File option from the Get-ChildItem cmdlet, and PowerShell will delete everything, including files and folders.

Delete Files Older Than x Days Using PowerShell

Delete files that are older than a certain number of days is another common example of disk space management. This example may be used to clear up disk space by eliminating old log files, such as those created by IIS web servers.

There are files older than 14 days in c:temp in this example. The Name, CreationTIme, and AgeInDays of each file in c:temp are shown using the script below.

Get-ChildItem c:temp | Select-Object Name,CreationTime,@n=’AgeInDays’;e=(New-TimeSpan -Start $PSItem.CreationTime).Days;e=(New-TimeSpan -Start $PSItem.CreationTime).Days;e=(New-TimeSpan -Start $PSItem.CreationTime).Days;e=(New-TimeSpan

There are files that are 15 days old, 7 days old, and 0 days old, as seen in the image below.

a list of the files in the c:temp directorya list of the files in the c:temp directory

Now that you know which files to delete, you can write a script that will only delete files older than a certain number of days — in this example, 14 days.

Files in C:temp whose CreationTime value is older than the defined threshold will be removed in this sample script.

The first line specifies the search path for Get-ChildItem. The $path variable is used to preserve the path. The threshold is then provided on the second line. The $threshold value indicates how old the file to be erased must be in days.

Following the $threshold variable, the following line of code will be:

  • Retrieve a group of files from the $path variable’s given folder. The path in this case is C:temp.
  • Filter the results to only include files with a CreationTime value that is greater than the number of days recorded in the $threshold variable. The criterion in this case is 14 days.
  • To delete such files, pipe the filtered list of files to the Remove-Item value.

‘C:Temp’ as $path $threshold = 14 $threshold = 14 $threshold = 14 -Path Get-ChildItem Where-Object $PSItem.CreationTime -lt $path -File (Get-Date). |Remove-Item -Verbose |AddDays(-$threshold)

When you execute the code above, you’ll get the following results.

The script removed files that were older than 14 days.The script removed files that were older than 14 days.

The script only destroyed five files older than 14 days, as seen in the picture above, based on the verbose notice. Run the code below to see whether files older than 14 days still exist.

Get-ChildItem c:temp | Select-Object Name,CreationTime,@n=’AgeInDays’;e=(New-TimeSpan -Start $PSItem.CreationTime).Days;e=(New-TimeSpan -Start $PSItem.CreationTime).Days;e=(New-TimeSpan -Start $PSItem.CreationTime).Days;e=(New-TimeSpan

Remove-Item did not remove the newer files, as seen in the results below.

Newer files are unaffected.Newer files are unaffected.

Matching and deleting file patterns using PowerShell

It is not always the ideal technique to delete all files, regardless of their name, kind, or extension. Certain files must be expressly excluded or included in the deletion procedure at times.

The following example demonstrates how to remove files with the filename *.LOG. One method is to use the Remove-Item cmdlet directly using the -Include argument, as demonstrated in the example below.

-Path C:temp* -Include *.log Remove-Item

Another option is to use Get-ChildItem first to get the list of files to be destroyed, which is arguably the most conservative technique. Finally, pass the collection to the Remove-Item cmdlet if you’re happy with the list of files to delete.

The code below, for example, creates *.LOG files in c:temp.

-Path C:temp* -Include *.log Get-ChildItem

Get-ChildItem produces a list of files that match the *.LOG filename as a consequence of the code above.

Only files with the filename *.log are returned.Only files with the filename *.log are returned.

But what if you wish to exclude a file whose name includes the number 5? You may do so by using the -Exclude argument, as seen in the following code.

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

The result has changed because you removed the file with the number 5. The file File 5.log, for example, is no longer in the list, as seen below.

The file File 5.log was not included in the analysis.The file File 5.log was not included in the analysis.

You may pipe the files collection to the Remove-Item cmdlet to destroy the files if you’re pleased with the collection of files that your code generates.

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

You will have accomplished your aim of eliminating just the files you specified after executing your final code.

Selecting and deleting filesSelecting and deleting files

Using WMI with PowerShell to delete files

Let’s move on to a more complex use case: utilizing WMI, now that you know how to utilize the basic Delete-Item cmdlet to remove files.

WMI is supported by PowerShell by default. WMI support implies that WMI queries and methods may be invoked directly from PowerShell. Yes, WMI isn’t only for administrators who utilized Visual Basic scripts in the early days of Windows.

In PowerShell 3.0, Microsoft included WMI-specific CIM cmdlets. The Get-CimInstance and Invoke-CimMethod CIM cmdlets will be used to remove files.

Delete a File using PowerShell and WMI

This example requires you know the location of the file you want to remove. The Cim DataFile class is used with the Get-CimInstance cmdlet to gather information about the file to delete, which is C:Temprandom.txt.

$file2delete = Get-CimInstance -ClassName Cim DataFile -Filter “Name”: “C:Temprandom.txt”: “Name”: “Name”: “Name”: “Name”: “Name”: “Name” $file2delete

The -Filter argument in the above code accepts a WQL style query. Some characters, notably the backslash, must be escaped when using WQL. Because the WQL escape character is also a backslash, the characters become double-backslash –.

The outcome of running the code above is displayed in the example below. C:Temprandom.txt information is stored in the $file2delete variable.

Using PowerShell with a WMI query to get a fileUsing PowerShell with a WMI query to get a file

Now that the information for the file C:Temprandom.txt has been received, the $file2delete variable can be used to pass the resultant object to the Invoke-CimMethod cmdlet. The -Name option of the Invoke-CimMethod cmdlet indicates the name of the method of the Cim DataFile class.

Invoke-CimMethod -Name Delete | $file2delete

The ReturnValue displays 0 in the screenshot below, indicating that the command was successful.

Using WMI and PowerShell, a file was effectively removed.Using WMI and PowerShell, a file was effectively removed.

Please see this link – Delete function of the CIM DataFile class for a list of potential ReturnValue codes.

In addition, the picture below reveals that CIM only erased the C:Temprandom.txt file after using the Invoke-CimMethod Delete() function. The other files were not deleted.

The file C:Temprandom.txt was removed.The file C:Temprandom.txt was removed.

Delete All Files in a Folder Using PowerShell and WMI

Show you how to remove all files in a folder using PowerShell and WMI in the following example. Get-CimInstance and Invoke-CimMethod, which were used in the previous example, will be utilized again. This time, though, the WQL query will return all files in the folder rather than just one.

The Get-CimInstance cmdlet finds all files in C:temp in the following code. The query filters the Drive and Path fields of the Cim DataFile class, as shown below.

Get-CimInstance -ClassName Cim DataFile -Filter $file2delete “Path = ‘temp’ AND Drive = ‘c:’”

The information about the files in C:temp is saved in the $file2delete variable after running the code above. The result of inspecting the value(s) of the $file2delete variable is shown below.

Using WMI, create a list of all folders detected in c:temp.Using WMI, create a list of all folders detected in c:temp.

The $file2delete variable’s contents may now be fed to the Invoke-CimMethod to delete all files in c:temp.

Invoke-CimMethod -Name Delete | $file2delete

Remember that a ReturnValue value of 0 indicates that the delete procedure was successful, and each file that was deleted will have its own ReturnValue code.

Using WMI, all files in c:temp were removed.Using WMI, all files in c:temp were removed.

Delete Files By Extension Using PowerShell and WMI

You saw how to remove all files in a folder regardless of extension in the previous example. You may, however, choose which files are destroyed depending on their extension.

In the code below, you’ll note that the query now contains one additional condition (Name LIKE’percent.log). Only files with the.LOG extension will be returned as a result of this additional criterion. The percent (%) symbol is a LIKE operator in WQL that indicates “A string of zero or more characters.” The percent is the programming counterpart of the asterisk (*) character, which is a wildcard.

$file2delete = Get-CimInstance -ClassName cim_datafile ` -Filter “Drive = ‘c:’ AND Path = ‘\temp\’ AND Name LIKE ‘%.log’” Invoke-CimMethod -Name Delete | $file2delete

Before running the code above, there are nine *.LOG files and just one *.TXT file, as seen in the example below. The *.LOG files are destroyed after the code has finished executing, leaving just the *.TXT file in the folder.

Using WMI to delete files by extensionUsing WMI to delete files by extension

When WMI and Remove-Item are compared, WMI comes out on top.

You’ve gained a comprehensive idea of how to use PowerShell to remove files so far in this article. Remove-Item and WMI are two concepts you’ve studied about. Both serve the same purpose, but in very different ways.

Which approach, Remove-Item or WMI, should you use to remove files?

Getting and deleting files using PowerShell’s built-in cmdlets like Get-ChildItem and Remove-Item is significantly quicker than using WMI.

The comparison below illustrates how to acquire a list of files under the C:windowsweb directory and its subdirectories using WMI and the built-in PowerShell cmdlet.

## Using Get-ChildItem Measure-Command C:WindowsWeb -Recurse, list all files in C:WindowsWeb recursively. Get-CimInstance -ClassName Cim DataFile -Filter Get-CimInstance -ClassName Cim DataFile -Filter Get-CimInstance -ClassName Cim DataFile -Filter Get-CimInstance -ClassName Cim DataFile -Filter Get-CimInstance -ClassName Cim DataFile -Filter Get-CimInstance – “Path = ‘windowsweb percent’ AND Drive = ‘c:’”

If you execute the code above in PowerShell, you’ll get something like this.

With WMI Query, Get-ChildItem vs. Get-CimInstanceWith WMI Query, Get-ChildItem vs. Get-CimInstance

As you can see from the result above, displaying the files under C:windowsweb took roughly ten times longer using Get-CimInstance than it did using Get-ChildItem!

Did you notice that the Get-ChildItem line is much shorter than Get-CimInstance? With Gain-ChildItem, you not only get quicker execution, but you also get cleaner, shorter code.

Steps to Follow

You’ve seen two distinct methods to remove files with PowerShell, using built-in cmdlets and WMI/CIM, in this post.

To delete files, you should always use the Get-ChildItem and Remove-Item cmdlets. When compared to WMI, these built-in cmdlets are more versatile, simpler, and quicker to utilize.

Make an attempt to write a script that would clean up your disk space for you. Sure, there are some scripts available for that purpose; feel free to use them as a guide, but if you’re prepared to practice and learn, you should attempt to write your own.

Additional Reading

The “powershell remove-item if exists” is a PowerShell command that will delete files. It can be used with the “-Force” switch to overwrite any existing files without prompting for confirmation.

Frequently Asked Questions

How do I delete multiple files in PowerShell?

A: You can use the wildcard character * to match multiple files at once. For example, deleting all .txt files in a folder would be done with the command $files = Get-ChildItem *.TXT; Remove-item -Path $files

How do I delete files and folders in PowerShell?

A: There is no way to delete files or folders in PowerShell without an external program, such as Windows Explorer.

How do I force delete a file in PowerShell?

A: To force delete a file in PowerShell, you would use the rm command. For example, if you wanted to remove all files from your current working directory, this is what it looks like:

Related Tags

  • remove-item powershell
  • powershell remove-item force
  • powershell delete files matching pattern
  • powershell delete files in folder
  • powershell script to delete files from multiple folders

Table of Content