How to delete files with Powershell

1. Delete a folder and everything in it

With Powershell you can easily delete folders and files with the command line. Use the snippet below to first check if the folder exists, and if it does, delete it.

$Folder = 'D:\directory\to\delete'

"Test to see if folder [$Folder]  exists"
if (Test-Path -Path $Folder) {
    "Folder exists, delete directory and all content inside it"
    Remove-Item $Folder -Recurse -Force
}

Note: it is always a good practice to check if the folder exists before trying to delete it with Remove-Item, as calling this remove statement on a folder which doesn’t exist will throw an error.

By Leendert de Borst

Freelance software architect with 10+ years of experience. Expert in translating complex technical problems into creative & simple solutions.

Leave a comment

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