Skip to content

Instantly share code, notes, and snippets.

@jcefoli
Created February 15, 2025 08:12
Show Gist options
  • Save jcefoli/b62425248b2d5e01cc432d70c7c669b4 to your computer and use it in GitHub Desktop.
Save jcefoli/b62425248b2d5e01cc432d70c7c669b4 to your computer and use it in GitHub Desktop.
Move all contents of a directory for future disposal
<#
.SYNOPSIS
Moves contents from one directory to a temporary deletion folder.
.DESCRIPTION
This script safely moves files and folders from a specified directory to a randomly named
temporary folder. It preserves the original directory structure and handles the move operation
with error suppression.
Why? When you need to delete a directory such as a large .NET app webroot, there can be hundreds of
thousands of files and folders. Deleting such a large directory can take a long time. For lightning fast
CI/CD, we need to clear this out so the code can be replaced as quickly as possible
#>
$StartTime = Get-Date
$sourcePath = "C:\Web\LargeWebroot"
$destinationBasePath = "C:\Temp\ToDelete"
# Generate a random number for the destination folder
$randomNumber = Get-Random -Maximum 1000000
$destinationPath = Join-Path $destinationBasePath $randomNumber
# Create the destination folder if it doesn't exist
if (-not (Test-Path $destinationPath)) {
New-Item -Path $destinationPath -ItemType Directory
}
# Move all files and subfolders to the new destination
Get-ChildItem -Path $sourcePath -Recurse | ForEach-Object {
$dest = Join-Path $destinationPath -ChildPath $_.FullName.Substring($sourcePath.Length)
$destDir = Split-Path $dest
# Check if the destination directory exists before creating it
if (-not (Test-Path $destDir)) {
New-Item -ItemType Directory -Path $destDir
}
Move-Item -Path $_.FullName -Destination $dest -Force -ErrorAction SilentlyContinue
}
$FinishTime = Get-Date
$TotalTime = ($FinishTime - $StartTime).TotalSeconds
Write-Host "This took $TotalTime s."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment