PowerShell 测试列表中的文件名是否存在于目录中的某处并导出丢失

PowerShell Test If a Filename From a List Exists Somewhere In a Directory and Export Missing

我对此进行了研究,但未能提出可靠的解决方案。基本上,我有一个包含数千个音乐文件的单独硬盘。我有一个 CSV 列表,其中包含应该在硬盘驱动器中的所有文件的名称。示例:

My List

我希望能够测试我列表中的每个文件是否存在于硬盘中,如果不存在,则将其导出到单独的 "missing files" 列表。问题是硬盘驱动器中的每个文件都存在于多个文件夹下。

就像我现在的脚本一样,我正在尝试使用 join-path 测试路径是否存在。这是我现在的代码——它返回目录中的所有文件,而不仅仅是丢失的文件:

$documents = 'C:\Users\Me\Documents\ScriptTest'
$CSVexport = 'C:\Users\Me\Documents\ScriptTest\TestResults.csv'

$obj = @()
    Write-host "`n_____Results____`n" #Write the results and export to a CSV file
    $NewCsv = Import-CSV -Path 'C:\Users\Me\Documents\ScriptTest\Test.csv' |
        Select-Object ID,'File Path' |  
            ForEach-Object {
                if (!(Test-Path (Join-Path $documents $_.'File Path'))){
                    write-host "`n$($_.'File Path') is missing from the folder.`n"
                    $ObjectProperties = @{
                        ID = $_.ID
                        'File Path' = $_.'File Path'
                    }
                $obj += New-Object PSObject -Property $ObjectProperties
                }
            }
            $obj | export-csv $CSVexport -NoTypeInformation

如何计算每个文件不同的子目录?


编辑 - 已解决

$myFolder = 'C:\Users\Me\Documents\ScriptTest'
$CSVexport = 'C:\Users\Me\Documents\ScriptTest\Results.csv'
$csvPath = 'C:\Users\Me\Documents\ScriptTest\Test.csv'

$FileList = Get-ChildItem $myFolder -Recurse *.wav | Select-Object -ExpandProperty Name -Unique
Import-CSV -Path $csvPath | 
    Where-Object {$FileList -notcontains $_.'File Path'} |
    export-csv $CSVexport -NoTypeInformation

您可以从递归文件夹生成文件名列表,然后检查该文件是否在该列表中。

$documents = 'C:\Users\Me\Documents\ScriptTest'
$CSVexport = 'C:\Users\Me\Documents\ScriptTest\TestResults.csv'

$FileList = Get-ChildItem $documents -Recurse |
    Where-Object { -not $_.PSIsContainer } |
    Select-Object -ExpandProperty Name -Unique
Import-CSV -Path 'C:\Users\Me\Documents\ScriptTest\Test.csv' | 
    Where-Object {$FileList -notcontains $_.File} |
    Export-CSV $CSVexport -NoTypeInformation

编辑:根据 Bruce Payette 和 mklement0

的建议更新了答案以与 PowerShell 2.0 一起使用