Textfile contains full path of each file, all these need to be copied while preserving folder structure
C:\test2\sample2.jpg
G:\test3\folder1\sample3.mov
C:\test6\fol der1 \sample77.iso
D:\test3\folder1\fo $der2\sample5.mkv
New to powershall so this is the code i tried
$destination = "C:\copy_folder"
"C:\filelist.txt"
Get-Content $textFileWithPaths | % {
$NewFolder = Split-Path (Join-Path $destination $_) -Parent | Split-Path -NoQualifier`
If(!(Test-Path $NewFolder)){
New-Item -ItemType Directory -Path $NewFolder -Force
}
Copy-Item $_ $NewFolder -Force
}
Thanks
CodePudding user response:
The main issue I'm seeing is that you're not removing the Root of each path from your file before joining them with their new destination.
Basically, this part:
Split-Path (Join-Path $destination $_) -Parent | Split-Path -NoQualifier
Should be:
Split-Path $_ -NoQualifier | Join-Path $destination -ChildPath { $_ }
This should do the trick:
$destination = (New-Item C:\copy_folder -ItemType Directory -Force).FullName
Get-Content $textFileWithPaths | ForEach-Object {
$path = Join-Path $destination $_.Substring([IO.Path]::GetPathRoot($_).Length)
$null = [IO.Directory]::CreateDirectory([IO.Path]::GetDirectoryName($path))
Copy-Item -LiteralPath $_ -Destination $path
}