首页 > 解决方案 > 将 PowerShell 中的数组与文件目录进行比较 效率低下

问题描述

我对 PS 并不完全陌生,但我在没有方向的情况下完成了所有工作,这使得学习变得困难,因为有些事情我不知道我不知道。话虽如此,我有一个功能齐全的脚本,我想知道如何加快速度,或者可能获得一种完全不同的方式来完成它。

问题: 我在一个文件夹中有一堆照片,我需要将它们与 SQL 表中的 ID 列表进行比较。如果我找到匹配项,那么我需要将该照片移动到另一个目录进行处理

我知道这是低效的,因为我在 ID 循环的每次迭代中都调用了该目录,但是如果我尝试创建一个文件数组来检查然后比较这两个数组,我就无法让它工作。

同样,功能很棒,只是速度不快。

CLS

$startDate = Get-Date
$startDate

$photoSourceLocation = "C:\Temp\Photos\Aggregate" #"C:\Temp\Photos\Moved"
$photoDropLocation = "C:\Temp\Photos\Process"

$IdQuery = "SELECT ST.Id FROM SomeTable as ST"


$patients = Invoke-Sqlcmd -Query $IdQuery -ServerInstance "SQLServer" -Database "DB"
$photos = GCI $photoSourceLocation -File

$patientRaw = $patients | Measure 
$patientCount = $patientRaw.Count

#$PatientCount
$I = 1
$Out= ""

forEach ($patient in $Patients)
        {
        $MovePhoto = GCI $photoSourceLocation -File | Where-Object {$_.BaseName -contains $patient.Id}
        if($MovePhoto)
        {
        Move-Item $movePhoto.FullName -Destination $photoDropLocation 
        }
        #$MovePhoto.FullName
        Write-Progress -Activity "Processing photo matches." -Status "Progress:" -PercentComplete ($I/$patientRaw.count*100) #-End $Out
        $I++        
        }

$endDate = Get-Date     
$endDate

标签: arrayspowershellloops

解决方案


这是测试 CSV 导入中的项目与文件名集合中的项目之间匹配的一种方法。这取决于对-match集合而不是单个项目使用时的工作方式。

# fake reading in a CSV file
#    in real life, use Import-CSV
$InStuff = @'
ID
Zero000
Alpha111
Bravo222
Charlie333
Santa666
'@ | ConvertFrom-Csv

# fake reading in a list of file names
#    in real life, use Get-ChildItem
$FileList = @(
    [System.IO.FileInfo]'Alpha111.jpg'
    [System.IO.FileInfo]'Charlie333.jpg'
    [System.IO.FileInfo]'Santa666.jpg'
    )

foreach ($IS_Item in $InStuff)
    {
    # this depends on there only being ONE matching file
    $FoundFile = $FileList -match $IS_Item.ID

    if ($FoundFile)
        {
        'Found a file for     = {0}' -f $IS_Item.ID
        '    The file name is = {0}' -f $FoundFile.Name
        }
        else
        {
        Write-Warning ('No matching file was found for {0}' -f $IS_Item.ID)
        }
    }

输出 ...

WARNING: No matching file was found for Zero000
Found a file for     = Alpha111
    The file name is = Alpha111.jpg
WARNING: No matching file was found for Bravo222
Found a file for     = Charlie333
    The file name is = Charlie333.jpg
Found a file for     = Santa666
    The file name is = Santa666.jpg

推荐阅读