0

我比较文件夹内的文件。在此文件夹中,一些文件以两种文件格式存在(filename1.jpg、filename1.bmp、...),而一些文件仅以一种格式存在。我尝试查找所有仅以 .bmp 格式存在的文件并将其删除。

到目前为止我得到的代码是:

$jpg = Get-ChildItem "C:\..\" -File -Filter *.jpg | ForEach-Object -Process {[System.IO.Path]::GetFileNameWithoutExtension($_)}
$bmp = Get-Childitem "C:\..\" -File -Filter *.bmp | ForEach-Object -Process {[System.IO.Path]::GetFileNameWithoutExtension($_)}

Compare-Object $jpg $bmp | where {$_.SideIndicator -eq  "=>"} 

这列出了我正在寻找的文件,但我无法删除它们。我尝试了一些类似的东西:

Compare-Object $jpg $bmp | where {$_.SideIndicator -eq  "=>"} | ForEach-Object {
    Remove-Item  "C:\..\($_.FullName)"
    }

但没有任何成功。有没有人提示我如何解决这个问题?

4

1 回答 1

0

在您的 foreach 中,您的变量不是文件,而是比较的结果。

试试这个:

$a = Get-ChildItem "D:\a" -File -Filter *.jpg
$b = Get-Childitem "D:\b" -File -Filter *.bmp
Compare-Object $a.BaseName $b.BaseName | where {$_.SideIndicator -eq  "=>"}  | foreach {
    $name = $_.InputObject
    $File = $b.Where({$_.BaseName -eq $name})

    if ($File.Count -gt 1) {
        throw "Conflict, more than one file has the name $name"
    } else {
        Remove-Item -Path $File.FullName
    }
}
于 2020-02-11T11:20:14.173 回答