Created
March 21, 2025 01:37
-
-
Save potchy/367803835dd60abaa71c9d3db24737de to your computer and use it in GitHub Desktop.
Flatten folder
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Define input and output directories | |
$input = "C:\Users\John\input" | |
$output = "C:\Users\John\output" | |
# Ensure the output directory exists | |
if (-not (Test-Path -Path $output)) { | |
New-Item -ItemType Directory -Path $output | |
} | |
# Get full paths (to avoid relative path confusion) | |
$inputFull = (Get-Item $input).FullName | |
$outputFull = (Get-Item $output).FullName | |
# Get all files recursively from the input directory | |
Get-ChildItem -Path $inputFull -Recurse -File | ForEach-Object { | |
$file = $_ | |
# Get the relative path from input directory | |
$relativePath = $file.DirectoryName.Substring($inputFull.Length).TrimStart('\') | |
# Replace backslashes in the relative path with underscores | |
$relativePathUnderscore = $relativePath -replace '\\', '_' | |
# Create the new file name with relative path included | |
if ($relativePathUnderscore -ne '') { | |
$newFileName = "${relativePathUnderscore}_$($file.Name)" | |
} else { | |
$newFileName = $file.Name | |
} | |
# Define the destination path | |
$destination = Join-Path -Path $outputFull -ChildPath $newFileName | |
# Copy the file | |
Copy-Item -Path $file.FullName -Destination $destination -Force | |
Write-Host "Copied '$($file.FullName)' to '$destination'" | |
} | |
Write-Host "All files have been copied successfully." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment