PowerShell is a powerful scripting language that enables users to automate administrative tasks on Windows systems. One of the most common operations performed in PowerShell is deleting files. The Remove-Item cmdlet provides a simple and efficient way to delete files using PowerShell. In this blog post, we will explore the usage of the Remove-Item cmdlet and provide multiple examples to demonstrate its capabilities.
Table of Contents
PowerShell Remove-Item Alias
Although the best practice when scripting in PowerShell is using the full cmdlet name, it may be convenient to use their shortened aliases sometimes, especially when interacting with commands.
The PowerShell Remove-Item cmdlet has a few aliases that you should know. To find them, run the following command.
Get-Alias -Definition Remove-Item
Based on the result, Remove-Item cmdlet aliases are del, erase, rd, ri, rm, and rmdir.
Running any of these aliases means you’re executing the PowerShell Remove-Item cmdlet.
Basic Usage
The Remove-Item cmdlet allows you to delete files by specifying their paths. Here’s a basic example:
Remove-Item -Path .\dummy_files\4k2h8ux1z9.txt
In this example, we use the -Path parameter to specify the file path we want to delete. Replace “.\dummy_files\4k2h8ux1z9.txt” with the actual path of the file you want to delete. This command will delete the specified file.
Delete Multiple Files
Remove-Item also supports deleting multiple files at once. You can use wildcards to match multiple files based on a pattern.
Delete All Files
For example, you can run the following command if you want to delete all files in a given folder. The wildcard “*” represents all filenames in the folder. The -Verbose switch is only added to return the Remove-Item status.
Remove-Item -Path ".\dummy_files\*" -Verbose
Delete Files with Specific Extensions
In my folder called .\dummy_files, I have multiple files with different file extensions.
Get-ChildItem .\dummy_files | Group-Object Extension
What if you want to delete files with “.txt” extensions only? The PowerShell Remove-Item cmdlet allows you to do that too.
Remove-Item -Path .\dummy_files\*.txt -Verbose
As shown below, the command only deleted the files matching the *.txt extension.
Another way to delete specific file extensions is by using the -Include parameter. This parameter allows you to specify multiple values and include multiple filename extensions. For example, the command below deletes all *.txt and *.etl files.
Remove-Item -Path .\dummy_files\* -Include *.txt, *.etl -Verbose
Delete Files Excluding Specific Extensions
On the other hand, you can also delete all files while excluding files based on a pattern or extensions. You can do so by using the -Exclude parameter. For example, the command below deletes all files in the folder except those with *.log and *.jpg extensions.
Remove-Item -Path .\dummy_files\* -Exclude *.log, *.jpg -Verbose
The result below shows the command deleted all files except those with *.log and *.jpg extensions.
Delete Folder and Contents Recursively
Deleting a folder and all contents recursively can also be done with the PowerShell Remove-Item cmdlet through the -Recurse switch.
For example, my folder .\dummy_files has a folder structure like this:
tree .\dummy_files\ /F
The top folder, “dummy_files,” has one subfolder called “sub1”, which has another subfolder called “sub2”. Each folder has files under them.
To delete the subfolders and all their contents, run the following command.
Remove-Item -Path .\dummy_files\* -Recurse -Verbose
The results show two operations: Remove Directory and Remove File.
Notice that the top folder “dummy_files” was not deleted. The reason is the path we specified is “.\dummy_files\*” – which indicates to delete the items below the given path.
If we want to include the top folder in the deletion, remove the “\*” from the path.
Remove-Item -Path .\dummy_files -Recurse -Verbose
Now you can see the top folder “dummy_files” is also deleted.
PowerShell Script to Delete Files Older Than a Given Date
File deletion is a standard system administration task. This task is typically performed against old files no longer required to be on the system. In this section, we’ll write a starter PowerShell script to delete files older than a given date.
A Simple One-Liner
Suppose you want to delete files that are older than seven days. The first step is to initialize a variable to hold this date.
$Before = (Get-Date).AddDays(-7)
Next, specify the path to delete the files in another variable.
$Path = ".\dummy_files"
Retrieve the list of files that matches the “before date” condition using the Get-ChildItem cmdlet and pipe the result to the Remove-Item cmdlet.
Get-ChildItem -Path $Path -Recurse | ` Where-Object { $_.CreationTime -lt $Before } | ` Remove-Item -Force -Verbose
That script is the simplest form you can implement. But it would be better to enhance the script, such as accepting parameters and returning results.
Enhancing the Script
Copy the code below and save it as DeleteFiles.ps1 on your computer.
# DeleteFiles.ps1 param ( [Parameter(Mandatory)] [string] $Path, [Parameter(Mandatory)] [DateTime] $BeforeDate, [Parameter()] [switch] $Delete ) $files = Get-ChildItem -Path $Path | Where-Object { $_.CreationTime -lt $BeforeDate } | Select-Object FullName, CreationTime, @{ n = 'Age'; e = { ($(New-TimeSpan -Start $($_.CreationTime) -End (Get-Date))).Days } } $files | Add-Member -Name Deleted -MemberType NoteProperty -Value $false foreach ($item in $files) { if ($PSBoundParameters.ContainsKey('Delete')) { try { Remove-Item -Path $($item.FullName) -Force -ErrorAction Stop $item.Deleted = $true } catch { $_.Exception.Message | Out-Default $item.Deleted = $false } } return $item }
The script, “DeleteFiles.ps1,” is designed to delete files based on specified criteria. Let’s go through the script and understand its functionality step by step:
- The script expects three parameters:
- $Path: Specifies the path to the directory where the files are located. It is marked as mandatory, meaning it must be provided when running the script.
- $BeforeDate: Specifies the cutoff date. Files created before this date will be considered for deletion. It is also marked as mandatory.
- $Delete: This is a switch parameter. If provided, it indicates that the files should be deleted. It is not mandatory to include this parameter when executing the script.
- Get-ChildItem and Filtering:
- The script uses the Get-ChildItem cmdlet to retrieve the files in the specified directory ($Path). The results are piped to Where-Object to filter the files based on the creation date. Only files with a creation time earlier than the $BeforeDate value are selected.
- Selecting and Calculating Additional Information:
- After filtering the files, the script uses Select-Object to choose specific properties of the files: FullName (full path to the file), CreationTime (the file’s creation timestamp), and a calculated property named Age.
- The Age property calculates the days between the file’s creation time and the current date using the New-TimeSpan cmdlet.
- Adding a Custom Property:
- The script uses the Add-Member cmdlet to add a custom property called Deleted to each file object. By default, its value is set to $false for all files.
- Looping Through Files and Deleting (if specified):
- The script then enters a foreach loop to iterate over each file object.
- If the $Delete switch parameter is provided when executing the script, the script attempts to delete the file using Remove-Item.
- The Force parameter is used to delete files forcefully;
- And ErrorAction Stop ensures that errors during deletion will be caught and processed.
- Handling Exceptions:
- If an exception occurs during the deletion process, the error message is displayed using Out-Default, and the Deleted property of the file object is set to $false.
- Returning File Objects:
- Finally, the script calls the $item variable with each loop. Each file object will be returned individually when the script is executed.
This script lets you retrieve files in a specified directory created before a specific date. If the $Delete switch parameter is included, it will attempt to delete those files and provide feedback on whether each was successfully deleted.
Running the Script
To run the script, execute the below command. This command will execute the “DeleteFiles.ps1” script with the specified parameters. It will target the “dummy_files” directory, consider files created more than six days ago, and delete those files.
.\DeleteFiles.ps1 -Path .\dummy_files\ -BeforeDate (Get-Date).AddDays(-6) -Delete
Conclusion
The PowerShell Remove-Item cmdlet provides a powerful and efficient way to delete files and folders. With its extensive range of options and flexibility, you can quickly delete individual files and entire directories or filter files based on specific criteria. By understanding the different parameters and syntax of the Remove-Item cmdlet, you can confidently manage your files and keep your system organized.
Remember to exercise caution when using PowerShell to delete files, as it permanently removes them from your system. Always double-check your commands and verify the items you intend to delete. Additionally, ensure you have the necessary permissions to delete files and folders.
PowerShell’s Remove-Item cmdlet can streamline your file management tasks and automate deletion processes, saving you time and effort. Whether you’re a system administrator, developer, or power user, mastering PowerShell’s Remove-Item cmdlet is a valuable skill to have in your toolkit.