PowerShell Guide: Deleting Files and Folders

If you find yourself needing to delete files in PowerShell, especially as part of a Windows script, this post is for you. Below, we cover various aspects of file deletion using PowerShell, ranging from deleting individual files to removing entire folders and files within subfolders recursively.

PowerShell: Delete a File

The Remove-Item cmdlet is your go-to tool for deleting files or directories in PowerShell. You can delete files from the current directory or specify a path for more control. Take note of the syntax variations demonstrated below. Remember to use quotes around the path if dealing with directory names containing spaces.

# Delete file in the current directory
Remove-Item -Name testFile.txt

# Delete file in the specified directory
Remove-Item -Path C:\temp\demoFolder\testFile.txt

# Delete all files in the specified directory with .tmp file extension
Remove-Item "C:\temp\*.tmp"

PowerShell: Delete a Folder

Deleting a folder with PowerShell is straightforward. Use the same Remove-Item command as above. However, when dealing with folders, consider the files within them. The example below first deletes a folder within the current directory, followed by a script checking for folder existence before deletion.

# Delete a folder in the current directory
Remove-Item .\demoFolder\

# Delete folder if it exists, forcefully delete all files in the folder (excluding subdirectories)
$path = "C:\temp\demoFolder"
if (Test-Path $path) {
    Remove-Item $path -Force -Recurse

PowerShell: Delete Files in Subfolders Recursively

When you need to delete files within a folder and its subfolders, the script below comes in handy. Adjust the path and file type wildcard as needed.

# Delete all .txt files in the folder & subfolders
$path = "C:\temp\demoFolder"
if (Test-Path $path) {
    Get-ChildItem $path -Include *.txt -Recurse | Remove-Item
PowerShell Delete Files in Folder

Additionally, it’s worth noting that gci used in the scripts above is an alias for Get-ChildItem.

Leave your thoughts or questions in the comments section below!

Leave a Reply

Your email address will not be published. Required fields are marked *