Reputation: 13
I am trying to copy all folders (and all files) from one folder to another in Powershell where the folders are listed in a text file. I have a script that successfully copied the folders, but the files did not copy over.
$file_list = Get-Content C:\Users\Desktop\temp\List.txt
$search_folder = "F:\Lists\Form601\Attachments\"
$destination_folder = "C:\Users\Desktop\601 Attachments 2021b"
foreach ($file in $file_list) {
$file_to_move = Get-ChildItem -Path $search_folder -Filter $file -Recurse -ErrorAction SilentlyContinue -Force | % { $_.FullName}
if ($file_to_move) {
Copy-Item $file_to_move $destination_folder
}
}
List.text contains folders like:
4017
4077
4125
Upvotes: 1
Views: 2532
Reputation: 392
for file with full link
$folder_list = Get-Content -Path 'E:\Documents\copyFilesFromList\new 2.txt'
<#
pattern the *.txt is
E:\MUSIC\Parni Valjak\2009 - The Ultimate Collection\2009-The Ultimate Collection CD2\1.09. ...A Gdje Je Ljubav.flac
E:\MUSIC\Parni Valjak\2015 - Original Album Collection, Vol. 1 (5CD)\Parni Valjak-1984-Uhvati ritam-NoScans\10. ...I Na Kraju.flac
E:\MUSIC\Parni Valjak\2013 - Nema Predaje (mp3_320 delux)\2013 - Nema Predaje CD 2\2.01. 700 Milja Od Kuće.mp3
E:\MUSIC\Parni Valjak\1979 - Gradske price (1998, Hi-Fi Centar-CDD 10179)\01. 700 Milja Od Kuće.flac
#>
$destination_folder = 'E:\Downloads\Parni Valjak\'
$null = New-Item -Path $destination_folder -ItemType Directory -Force
$counter = 0
if (Test-Path -Path "$folder_list", "$destination_folder") {
foreach ($folder in $folder_list) {
if (Test-Path -Path $folder_list -PathType Container) {
# copy the folder including all files and subfolders to the destination
++$counter
Write-Host "$counter Copying files $folder"
Copy-Item -Path $folder -Destination $destination_folder
}
else {
Write-Warning "Folder '$folder' not found.."
}
}
}
else {
Write-Output "isn't exist"
}
Upvotes: 0
Reputation: 61028
I would use Test-Path
on each of the folders in the list to find out if this folder exists. If so do the copy.
$folder_list = Get-Content -Path 'C:\Users\Desktop\temp\List.txt'
$search_folder = 'F:\Lists\Form601\Attachments'
$destination_folder = 'C:\Users\Desktop\601 Attachments 2021b'
# first make sure the destination folder exists
$null = New-Item -Path $destination_folder -ItemType Directory -Force
foreach ($folder in $folder_list) {
$sourceFolder = Join-Path -Path $search_folder -ChildPath $folder
if (Test-Path -Path $sourceFolder -PathType Container) {
# copy the folder including all files and subfolders to the destination
Write-Host "Copying folder '$sourceFolder'..."
Copy-Item -Path $sourceFolder -Destination $destination_folder -Recurse
}
else {
Write-Warning "Folder '$folder' not found.."
}
}
Upvotes: 3