简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM