简体   繁体   English

通过将文件与文件夹名称匹配来将文件复制到文件夹的 Powershell 脚本

[英]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.我有一个包含空文件夹的目录,我们称之为 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.另一个目录(我们称之为 D2)包含命名为文件名包含来自 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.我想将 D2 中的文件名与 D1 中的文件夹名相匹配,并将文件复制(而不是移动)到 D1 中的相应文件夹中。 Can this be done using Powershell?这可以使用 Powershell 完成吗? As an example, D1 looks like:例如,D1 看起来像:

FolderName1
FolderName2
FolderName3

And files in D2 look like: D2 中的文件如下所示:

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.实际的文件夹/文件名可能会有所不同,例如Folder#NameMy_Folderabcd.1234.Folder_Name等。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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