从多个文件夹复制文件文件名是文件夹的一部分

问题描述 投票:0回答:1

'我正在尝试将多个文件夹中的多个文件复制到另一个文件夹中。文件夹中包含文件名的一部分。

例如 - 我想复制所有名称为“Phone”或“cell”的文件,并将序列号作为文件名的一部分。每个子文件夹都有序列号作为文件夹名称的一部分。

C:\shared\112\products\112.phone blah blah.txt
C:\shared\112\products\112.my cell.txt
C:\shared\113\products\113.ugly phone.txt
C:\shared\113\products\113.the cell.txt
C:\shared\114\products\114.pretty phone.txt
C:\shared\115\products\115.phone lazy.txt
C:\shared\115\products\115.celly cell.txt

问题是有20,000个序列号,所以我想设置一个序列号列表,并根据一组序列号拉取文件。这是我的剧本,但它没有拉动任何东西。

$FirstSearchlist = @(“112”, “113”)
$SecondSearchlist = @("phone","cell")

$dirArray = @("c:\Shared\")
$NotFound = "Not Found"

cls
function Recurse([string]$path) {

    $fc = new-object -com scripting.filesystemobject
    $folder = $fc.getfolder($path)

    foreach ($i in $folder.files) {

        [string]$FullPath = $i.Path
        [string]$FileName = $i.Name
        foreach($first in $FirstSearchlist) {
            if ($filename.ToUpper().Contains($first.ToUpper())) {
                foreach($second in $SecondSearchlist) {
                    if ($filename.ToUpper().Contains($second.ToUpper())) {
                        Write-Host $Fullpath
                         Copy-Item $Fullpath -Destination "C:\Shared\Phones" -Recurse
                                 }
                }
            }
        }
    }

    foreach ($i in $folder.subfolders) {
        Recurse($i.path)
    }
}

function main() {

    foreach ($i in $FirstSearchlist){
        $NewFolder = $dirArray + $i
        foreach($SearchPath in $NewFolder) {
            Recurse $SearchPath
        }
    }

}

main
shell powershell file copy
1个回答
0
投票

这对我来说可以使用提供的示例集进行测试(但在我的测试中注意C:\ Shared为空,可能需要根据您的文件夹树进行调整):

Function Get-FileMatches($Filter){
    $fileMatches = Get-ChildItem -Path "C:\Shared" -Recurse | ? {$_.Mode -notmatch 'd' -and $_.Name -match $Filter -and ($_.Name -match $SecondSearchlist[0] -or $_.Name -match $SecondSearchlist[1])}
    return $fileMatches
}

Function Run-Script() {

    $FirstSearchlist = @(“112”, “113”)
    $SecondSearchlist = @("phone","cell")
    $allMatches = @()

    $phonesFolderExists = Test-Path "C:\Shared\Phones"

    if($phonesFolderExists -eq $False)
    {
        New-Item -Path "C:\Shared\Phones" -ItemType Directory -Force
    }

    foreach($listItem in $FirstSearchList) {
        $currentMatches = Get-FileMatches -Filter $listItem
        if($currentMatches -ne $null)
        {
            foreach($item in $currentMatches)
            {
                $allMatches += $item
            }
        }
    }

    if($allMatches -ne $null)
    {
        foreach($item in $allMatches)
        {
            Copy-Item -Path $item.FullName -Destination "C:\Shared\Phones"
        }
    }
}

Run-Script
© www.soinside.com 2019 - 2024. All rights reserved.