繁体   English   中英

Powershell比较两个List与foreach

[英]Powershell comparing two List with foreach

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

我阅读了Compare-Object cmdlet,但是在这种情况下,我更喜欢使用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控件if($AllStartingFiles.Contains($file.Name)) ,该if($AllStartingFiles.Contains($file.Name))返回false。

输出值

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运算符,但是没有任何运气。

您在以下期间未解决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

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

我不知道使用比较对象的原因:

> tree /F
├───first
│       1_one.txt
│       2_two.txt
│       3_three.txt
│       5_five.txt
│
└───second
        1_one.txt
        2_two.txt
        3_three.txt
        4_four.txt
        5_five.txt

> compare (gci .\first\) (gci .\second\)

InputObject SideIndicator
----------- -------------
4_four.txt  =>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM