首页 > 解决方案 > Powershell 比较两个 List 和 foreach

问题描述

我正在尝试比较使用Get-ChildItemcmdlet 获得的两个列表。

我阅读了有关Compare-Objectcmdlet 的信息,但在这种情况下,我更喜欢使用 foreach,因为它对访问$file变量很有用。

$StartingFolderPath = "C:\---\StartingFolder"
$EndingFolderPath = "C:\---\EndingFolder"


$AllStartingFiles = Get-ChildItem $StartingFolderPath 
$AllEndingFiles = Get-ChildItem $EndingFolderPath

Write-Host "First folder content:"$AllStartingFiles 
Write-Host "Second folder content:" $AllEndingFiles  


foreach($file in $AllEndingFiles){

    write-Host "Element :" $file.Name

    $result = $AllStartingFiles.Contains($file.Name)
    write-host $result

    if($AllStartingFiles.Contains($file.Name)){
    Write-Host  "You are here"
    Write-Host $file.Name
    }    
}

但似乎我无法通过if($AllStartingFiles.Contains($file.Name))返回 false 的 if 控件。

输出

First folder content: 1_one.txt 2_two.txt 3_three.txt 5_five.txt
Second folder content: 1_one.txt 2_two.txt 3_three.txt 4_four.txt 5_five.txt 
6_six.txt
Element : 1_one.txt
False
Element : 2_two.txt
False
Element : 3_three.txt
False
Element : 4_four.txt
False
Element : 5_five.txt
False
Element : 6_six.txt
False

我也尝试过-Contains操作员,但没有任何运气。

标签: powershellforeachcontains

解决方案


您在期间没有解决该Name属性

$result = $AllStartingFiles.Contains($file.Name)

正确的方法是:

$result = $AllStartingFiles.Name.Contains($file.Name)

如果只是不想使用Compare-Object,因为你害怕你会丢失文件属性,但事实并非如此。

Compare-Object -ReferenceObject $AllEndingFiles -DifferenceObject $AllStartingFiles -IncludeEqual -ExcludeDifferent | Select-Object -ExpandProperty InputObject

这将为您提供出现在列表及其属性中的所有文件。


推荐阅读