powershelldirectory

Powershell script to copy folders/files from text file


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


Solution

  • 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.."
        }
    }