Public/Remove-FolderRecursive.ps1
function Remove-FolderRecursive { <# .SYNOPSIS Quickly removes a folder and all of it's contents .DESCRIPTION Performs a deletion of a folder and all of it's contents .PARAMETER Path Path .EXAMPLE Remove-Folder -Path 'C:\Delete-Me' #> [CmdletBinding()] # Always add CmdletBinding to expose the common Cmdlet variables param( [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true, # Make sure you have a process block if the function accepts value(s) from the pipeline ValueFromPipelineByPropertyName = $true)] [String] $Path ) begin { } process { ## ## Windows ## if ($IsWindows) { ## Check that the path is valid if (-Not (Test-Path -Path $Path )) { return } ## Create an Empty Folder $EmptyFolderPath = Join-Path -Path $env:TEMP -ChildPath (New-Guid).Guid New-Item -ItemType Directory $EmptyFolderPath | Out-Null ## Invoke Robocopy to remove ## Setup Standard Process Options $RobocopyProcInfo = New-Object System.Diagnostics.ProcessStartInfo $RobocopyProcInfo.FileName = 'C:\Windows\system32\Robocopy.exe' $RobocopyProcInfo.UseShellExecute = $false $RobocopyProcInfo.CreateNoWindow = $true $RobocopyProcInfo.WindowStyle = 'Hidden' ## Redirect Standard Streams # $RobocopyProcInfo.RedirectStandardError = $false # $RobocopyProcInfo.RedirectStandardOutput = $false # $RobocopyProcInfo.RedirectStandardInput = $false $RobocopyProcInfo.RedirectStandardError = $true $RobocopyProcInfo.RedirectStandardOutput = $true $RobocopyProcInfo.RedirectStandardInput = $true ## Add Process Arguments $RobocopyProcInfo.Arguments = '"' + $EmptyFolderPath + '" "' + $Path + '" ' $RobocopyProcInfo.Arguments += ' /MIR' ## Mirror to remove all files $RobocopyProcInfo.Arguments += ' /MT:8' ## Multi-thread, 8 $RobocopyProcInfo.Arguments += ' /NS' ## No Size Output $RobocopyProcInfo.Arguments += ' /NC' ## No Class Output $RobocopyProcInfo.Arguments += ' /NFL' ## No File List Output $RobocopyProcInfo.Arguments += ' /NDL' ## No Directory List Output $RobocopyProcInfo.Arguments += ' /NP' ## No Progress Output $RobocopyProcInfo.Arguments += ' /NJH' ## No Job Header $RobocopyProcInfo.Arguments += ' /NJS' ## No Job Summary ## Start the Robocopy $RobocopyProc = New-Object System.Diagnostics.Process $RobocopyProc.StartInfo = $RobocopyProcInfo try { ## Run the SSH Session [Void]$RobocopyProc.Start() ## Wait for the Process to Exit $RobocopyProc.WaitForExit() } catch { throw $_ } ## Close and Dispose the Exe $RobocopyProc.Close() $RobocopyProc.Dispose() ## Remove the Temp/Empty folder Remove-Item -Path $EmptyFolderPath -Force Get-ChildItem -Path $EmptyFolderPath -Force -Recurse | Remove-Item -Force -Recurse } } end { } } |