Disclaimer
This is my personal blog. The opinions and views I express are my own. The information I provide is on an as-is basis. I make no representations as to accuracy, completeness, currentness, suitability, or validity of any information on this blog and will not be liable for any errors, omissions, or delays in this information or any losses, injuries or damages arising from its use.

Script to delete multiple folders (Powershell)

This script will delete multiple folders and sub-folders. If the need to add other paths to delete just create more $path variables and copy and edit the IF statements.

I’ve tested this on Windows Server 2K3, Windows Server 2K8, Windows Server 2K8 R2, Windows Vista x32, Windows Vista x64, Windows 7 x32 and Windows 7 x64.

This can also be adapted you delete folders on remote systems by changing the $path to something like \\computername\C$\test or \\computername\sharename\WhateverFolderNameIs assuming your user has permissions to delete the folder.

# If you have other paths you need to delete just add more $path variables 
# and copy the If statements

$path = "c:\test"
$path2 = "c:\test2"

# Checks if $path exists, if so deletes it and all subfolders and files
if (Test-Path $path) {

    $path + " Exists"
    Remove-Item -path $path -recurse
    Write-host -foregroundcolor Red $path " Deleted"
    [System.Threading.Thread]::Sleep(1500)

    } else {

    Write-host -foregroundcolor Red  $path  " Does not exist"

    }

# Checks if $path exists, if so deletes it and all subfolders and files
if (Test-Path $path2) {

    $path2 + " Exists"
    Remove-Item -path $path2 -recurse
    Write-host -foregroundcolor Red $path2 " Deleted"
    [System.Threading.Thread]::Sleep(1500)

    } else {

    Write-host -foregroundcolor Red  $path2  " Does not exist"

    }

 

Alternately, you can remove the IF statements and just use this:

$path = "c:\test"
$path2 = "c:\test2"

Remove-Item -path $path -recurse

Remove-Item -path $path2 -recurse

 

1 Comment

  1. nash | | Reply

    how to use this script to delete folders on multiple remote servers?
    is it possible to generate a report of success/failures

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.