To copy only the lowest folder structures without files, you must use a script that identifies leaf directories and recreates their full parent paths in the destination. This approach ensures that intermediate directories exist before placing empty folders, preventing path errors while preserving the hierarchical integrity of your project structure.
Understanding the Problem with Recursive Copying
When managing large projects or migrating data, developers often need to replicate the directory tree without transferring the actual content. Standard commands likexcopy or robocopy in Windows, or cp -r in Linux/macOS, typically copy both files and folders. Filtering out files while maintaining the exact folder hierarchy can be tricky because many tools assume that if a folder exists, its contents are being copied as well.
The core challenge arises when you attempt to create only the "leaf" nodes (the deepest folders) in a new location. If you simply create these deepest folders without ensuring their parents exist, the operation fails. For example, trying to create /dest/a/b/c will fail if /dest/a/b does not already exist. Therefore, the solution requires two distinct steps: identifying the target directories and reconstructing the entire path from the root down to the leaf.
PowerShell Solution for Windows Users
For Windows environments, PowerShell provides the most robust method to handle this task safely. The following script finds all directories that do not contain subdirectories (leaf nodes) and copies their structure to a new location. First, define your source and destination variables. Ensure the destination path exists before running the script.$SourcePath = "C:\Your\Source\Folder"
$DestPath = "C:\Your\Destination\Folder"
# Get all leaf directories (directories with no subdirectories)
$LeafDirs = Get-ChildItem -Path $SourcePath -Recurse -Directory |
Where-Object { $_.GetDirectories().Count -eq 0 }
foreach ($Dir in $LeafDirs) {
# Calculate the relative path from the source root
$RelativePath = $Dir.FullName.Substring($SourcePath.Length).TrimStart('\')
# Construct the full destination path
$NewPath = Join-Path -Path $DestPath -ChildPath $RelativePath
# Create the directory, including all necessary parent folders
New-Item -ItemType Directory -Force -Path $NewPath
}
This script uses Get-ChildItem with the -Directory flag to isolate folders. The Where-Object clause filters for folders that have zero subdirectories, effectively finding the leaves. The critical part is New-Item -Force, which creates the entire path hierarchy, including any missing intermediate parents.
If you need to maintain timestamps during this process, refer to our guide on Maintaining Modified Time When Moving Files in File Explorer for Windows 11. While this script focuses on structure, understanding timestamp preservation helps in auditing changes.
Bash Solution for Linux and macOS
On Unix-like systems, thefind command combined with mkdir offers an efficient one-liner solution. This method leverages the shell's ability to process output streams directly.
find /path/to/source -type d -empty -exec mkdir -p /path/to/destination/{} \;
Let's break down how this works. The find command searches for items of type d (directory) that are -empty. Note that -empty checks if the directory contains no files or subdirectories. The -exec flag runs the mkdir -p command for each found directory. The -p flag is essential here; it tells mkdir to create parent directories as needed. Without -p, the command would fail if the parent path did not exist.
Replace /path/to/source and /path/to/destination with your actual paths. Be cautious with trailing slashes in the destination argument within the exec block. If the source path is /src/a/b, the command becomes mkdir -p /dest//a/b, which usually works but can look messy. A cleaner alternative involves using sed to replace the source prefix with the destination prefix.
find /src -type d -empty | sed 's|^/src|/dest|' | xargs -I {} mkdir -p {}
This pipeline finds empty directories, substitutes the source path with the destination path using sed, and then passes the resulting paths to mkdir via xargs. This method is highly performant for large directory trees.
Handling Special Characters and Spaces
Both solutions above handle spaces in folder names correctly due to proper quoting and argument parsing. However, if your folder names contain special characters like quotes or newlines, the Bashsed approach might require additional escaping. In such cases, using a loop with null-delimited output (find ... -print0) is safer but more complex to read. For most standard project structures, the provided snippets are sufficient.
Why Intermediate Parents Matter
A common mistake in custom file management scripts is assuming that creating a leaf node automatically creates its ancestors. Operating system APIs generally require explicit creation of each level in the hierarchy unless a recursive flag is used. By explicitly generating the full path, we avoid race conditions where multiple threads might try to create the same parent directory simultaneously. Using-Force in PowerShell or -p in Bash handles these conflicts gracefully by checking existence before creation.
For users interested in other file manipulation tasks, such as moving files based on extension, see Move Files with Different Extensions to Different Folders using PowerShell. Combining structure copying with selective file movement allows for sophisticated data organization workflows.
Troubleshooting Common Errors
If you encounter permission denied errors, ensure you have write access to the destination drive. On Windows, running the PowerShell script as an Administrator may be required if the destination is in a protected system folder. On Linux, check ownership usingls -ld on the destination root.
Another issue is infinite loops if symbolic links are present. Both Get-ChildItem and find can follow symlinks by default. To prevent this, add the -NoFollowSymlinks parameter in PowerShell or use -notype l exclusion in Bash if you want to ignore symlinked directories. Always test your script on a small subset of data first to verify behavior.
Frequently Asked Questions
Can I use this method to copy only hidden folders?
Yes, but you must include hidden items in your search query. In PowerShell, add the-Hidden flag to Get-ChildItem. In Bash, find includes hidden files by default, so no extra flags are needed for visibility.
What happens if a folder in the source is not empty?
The scripts specifically filter for empty leaf directories. Non-empty folders are ignored entirely. If you need to copy non-empty folders but exclude their contents, you would need a different logic that processes all directories but skips file transfers.Is there a GUI tool for this?
Most standard file explorers do not offer a "copy structure only" feature. Third-party tools like Total Commander or specialized backup software may offer this, but scripting remains the most flexible and free option for precise control.How do I delete these newly created empty folders later?
You can reverse the process by finding empty directories in the destination and deleting them. UseRemove-Item in PowerShell with Force, or rmdir in Bash. Be careful to point the command at the correct destination to avoid accidental data loss.
Does this preserve folder permissions?
The basic scripts provided do not explicitly copy NTFS permissions or Unix file modes. They rely on the default permissions of the destination parent directory. If specific permissions are required, you must use advanced parameters likeAcl in PowerShell or --preserve=mode in rsync for more complex scenarios.