<# FPS:Containers:Common:Public:Remove-DirTree:ACTIVE #>

 

function Remove-DirTree {

 

<#

 

.DESCRIPTION

Module: Common

Public CmdLet: Remove-DirTree.ps1

Dependencies: None

 

When deleting files recursively using a simple Remove-Item "folder" -Recurse I sometimes see an intermittent error : [folder] cannot

be removed because it is not empty.  This answer attempts to prevent that error by individually deleting the files.

  

.USAGE

Called throughout FPS to determine a CmdLet's existence.  Returns a boolean value

 

.EXAMPLE

if (Push-NeededFor Remove-DirTree)  { . (Get-ActiveFileNm -PS1 Remove-DirTree)  }

Remove-DirTree "D:\Todos"

 

Expected Result: The entire directory tree will be deleted individually

 

.CC

 

[2024.09.25 JD] Original code release

 

.NOTES

This answer attempts to prevent directory recursive delete errors by individually providing the files.

 

#>

 

 [CmdletBinding()]

    param(

    [Parameter(Position=0, Mandatory=$true)] [string]$Path

    )

 

    if (Test-Path $Path) {

        if ($PSBoundParameters.Verbose -eq $true) { Write-Verbose ("Deleting " + $Path) }

        try {

                #Remove-Item -Recurse doesnt work properly, so recurse through children and remove, then remove the target

                Get-ChildItem $Path -Recurse -File | Remove-Item -Force -Recurse

                Get-ChildItem $Path -Recurse -Directory | Remove-Item -Force -Recurse

                Remove-Item $Path -Force -Recurse

        }

        catch {

                if ($PSBoundParameters.Verbose -eq $true) { Write-Verbose $_.Exception.Message }

        }

 

        if ((Test-Path $Path)) {

                if ($PSBoundParameters.Verbose -eq $true) { Write-Verbose ("Failed to remove target folder '" + $Path + "'") }

        }

    }

 }