lamchau
2/26/2016 - 5:00 AM

multithreaded large folder delete on windows

multithreaded large folder delete on windows

# for deleting large directories (e.g. node_modules)
function purge($target_dir) {
  if (Test-Path -Path $target_dir) {
    $uuid = [guid]::NewGuid().toString()
    $empty_dir = "$env:temp$uuid.tmp"
    New-Item -ItemType directory -Path $empty_dir | Out-Null

    # delete using robocopy /NFL ... (options to suppress stdout)
    robocopy $empty_dir $target_dir /MIR /MT | Out-Null
    Remove-Item $empty_dir | Out-Null

    $target_dir = (Resolve-Path $target_dir).Path
    Remove-Item -Recurse -Force $target_dir | Out-Null
    Write-Output "Deleted: $target_dir"
  }
}