Last active
October 18, 2024 07:11
-
-
Save gravejester/9acf0c611ad1fce6aa456a7dd4ccec4b to your computer and use it in GitHub Desktop.
Function to copy a file while keeping the original folder structure (relative to the destination path)
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
function Copy-FileWithStructure($Path,$Destination) { | |
$fileObject = Get-Item -Path $Path | |
$pathParts = ($fileObject.Directory.ToString()).split([System.IO.Path]::DirectorySeparatorChar) | |
$newDestination = Join-Path -Path $Destination -ChildPath (($pathParts | Select-Object -Skip 1) -join([System.IO.Path]::DirectorySeparatorChar)) | |
$script:newPath = $Destination | |
# Loop through and re-create the folder structure | |
foreach ($pathPart in ($pathParts | Select-Object -Skip 1)) { | |
$newPath = Join-Path -Path $newPath -ChildPath $pathPart | |
if (-not(Test-Path -Path $newPath)) { | |
New-Item -Path $newPath -ItemType Directory | Out-Null | |
} | |
} | |
# Copy file to new location | |
Copy-Item -Path $Path -Destination $newDestination | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment