Skip to content

Instantly share code, notes, and snippets.

@gravejester
Last active October 18, 2024 07:11
Show Gist options
  • Save gravejester/9acf0c611ad1fce6aa456a7dd4ccec4b to your computer and use it in GitHub Desktop.
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)
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