Last active
February 16, 2016 13:20
-
-
Save FUNExtreme/931dd34d87203a605aa2 to your computer and use it in GitHub Desktop.
This script copies the children of a given directory to the specified destination directory
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
# | |
# This script copies the children of a given directory to the specified destination directory | |
# | |
# Created by FUNExtreme (Robin Maenhaut <[email protected]>) | |
# Script Parameters | |
Param( | |
[string]$srcDir, # The directory to copy the children from | |
[string]$destDir, # The directory to recreate the folder and file structure to | |
[switch]$wipeDest # Switch to indicate whether the destination folder should be wiped before copying | |
) | |
# Check if the user has terminated their directory paths with a backslash | |
if(!$srcDir.EndsWith("\")) | |
{ | |
$srcDir += "\" | |
} | |
if(!$destDir.EndsWith("\")) | |
{ | |
$destDir += "\" | |
} | |
# Check if there actually is anything at the specified source directory | |
if(Test-Path -Path $srcDir) | |
{ | |
# If the wipe destination switch is specified, recursivly remove files from the destination | |
# If one of the files can not be removed, we silently continue | |
if($wipeDest -And (Test-Path -Path $destDir)) | |
{ | |
Remove-Item -Path ($destDir + "*") -Recurse -Force -ErrorAction SilentlyContinue | |
} | |
# Copy source children to the destination | |
$srcChildren = Get-ChildItem -Path ($srcDir + "*") -Recurse | |
foreach($srcChild in $srcChildren) | |
{ | |
# We figure out the relative path of the file, this way we can maintain the folder structure in the destination | |
# Once we have the relative path, we then add it to the destination directory path in order to get the absolute file destination path | |
$childDestDirConstructed = $destDir + $srcChild.FullName.Substring($srcDir.Length).Replace($srcChild.Name, "") | |
# If the path destination folder of the child (which could be nested deeply within the root destination) doesn't yet exist, we create it first | |
if(!(Test-Path -Path $childDestDirConstructed)) | |
{ | |
New-Item -ItemType Directory -Path $childDestDirConstructed | |
} | |
# We copy the child to its destination | |
Copy-Item -Path $srcChild.FullName -Destination $childDestDirConstructed -Force | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment