简体   繁体   中英

Powershell script to copy files to folders by matching file to folder names

I have a directory with empty folders, let's call it D1. And another directory (let's call it D2) with files which are named such that the file name contains the folder names from D1. I want to match the file names from D2 to folder names from D1 and copy (not move) the files to the corresponding folder in D1. Can this be done using Powershell? As an example, D1 looks like:

FolderName1
FolderName2
FolderName3

And files in D2 look like:

abcd.FolderName1.txt
xyz.FolderName2.txt
qwerty.FolderName3.txt

EDIT: the folder names above are just an example. The actual folder/file names could vary eg to Folder#Name , My_Folder , abcd.1234.Folder_Name etc.

I pulled the folder names from the filename with regex. There's a little bit of error handling in there, but you might want to instead create the folder if it doesn't exist.

$FromPath = 'C:\D2'
$ToPath = 'C:\D1'

$FilesToMove = Get-ChildItem -Path $FromPath -File

$RegexPattern = '^[^.]+\.(?<NewFolder>[^.]+)\..+$'

foreach ($File in $FilesToMove) {
    If($File.Name -match $RegexPattern){
        $OutFolder = Join-Path -Path $ToPath -ChildPath $Matches.NewFolder
        if (Test-Path -Path $OutFolder) {
            Copy-Item -Path $File -Destination $OutFolder
        }
        else {
            Write-Error -Message "Invalid or Inaccesible path $OutFolder"
        }
    }
    else {
        Write-Error -Message "Filename $($File.Name) Is Incorrectly Formatted"
    }
}

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