Home » How to Delete Multiple File Extensions Using PowerShell

How to Delete Multiple File Extensions Using PowerShell

To delete multiple file extensions in a directory using PowerShell, use the Get-ChildItem and Remove-Item cmdlets.

The following method can be used to delete multiple file extensions in PowerShell.

Method 1: Delete multiple file extensions using PowerShell

# Define an array of file extensions
$extensions = "csv", "txt", "log"

foreach {$extension in $extensions) {
       Get-ChildItem -Filter "*.$extension" | Remove-Item
}

In this example, the Get-ChildItem cmdlet retrieves all files with multiple extensions and pipes them to the Remove-Item for deletion.

The following example shows how to use this method.

Delete Multiple File Extensions Using PowerShell

Use the Get-ChildItem cmdlet to retrieve all files with multiple extensions from the directory and the Remove-Item cmdlet to remove each file.

The following example shows how to use it with syntax.

# Specify the directory path
$directoryPath = "C:\temp\log\"

# Specify the multiple extension
$extensions = "csv","txt"

# Loop through the extension to retrieve all files and remove them
foreach($extension in $extensions) { 
   Get-ChildItem -Path $directoryPath -Filter "*.$extension" | Remove-Item
}

The output of the above PowerShell script deletes multiple file extensions (.csv and .txt) from the specified directory $directoryPath.

The foreach loop iterates through each extension in the $extensions array. For each extension, the Get-ChildItem cmdlet retrieves files in the specified directory with that extension and the output is piped to the Remove-Item command to delete those files.

After running this script, all files with the specified extensions in the given directory will be deleted.

Conclusion

I hope the above article on deleting multiple file extensions using PowerShell is helpful to you.

You can find more topics about Active Directory tools and PowerShell basics on the ActiveDirectoryTools home page.