比较对象不比较数组的每个元素

时间:2018-08-28 12:20:05

标签: powershell compareobject

我正在尝试使用Compare-Object查找位于一个数组($fileArray)中但不在另一个数组($dictionaryArray)中的元素。由于某些原因,Compare-Object仅比较fileArray中的最后两个元素。这是我要运行的代码。

$dictionary = Get-Content "C:\Users\Joe\Documents\PowerShell Scripts\Work\PCI Numbers\dictionary.txt"
$file = Get-Content "C:\Users\Joe\Documents\PowerShell Scripts\Work\PCI Numbers\file.txt"

$dictionaryArray = @()
$fileArray = @()

$dictionaryLength = $dictionary | Measure-Object -Line
$fileLength = $file | Measure-Object -Line

$i = 0

while($i -lt $dictionaryLength.Lines){
    $name = $dictionary | Select -Index $i
    $i++
    while($dictionary[$i] -ne " " -and $i -lt $dictionaryLength.Lines){
        $dictionaryObject = New-Object -TypeName PSObject
        $dictionaryObject | Add-Member -Name 'PC' -MemberType Noteproperty -Value $name
        $dictionaryObject | Add-Member -Name 'File' -MemberType Noteproperty -Value $dictionary[$i]
        $dictionaryArray += $dictionaryObject
        $i++
    }
    $i++
}

$i = 0

while($i -lt $fileLength.Lines){
    $name = $file | Select -Index $i
    $i++
    while($file[$i] -ne " " -and $i -lt $fileLength.Lines){
        $fileObject = New-Object -TypeName PSObject
        $fileObject | Add-Member -Name 'PC' -MemberType Noteproperty -Value $name
        $fileObject | Add-Member -Name 'File' -MemberType Noteproperty -Value $file[$i]
        $fileArray += $fileObject
        $i++
    }
    $i++
}

$i = 0

Compare-Object -ReferenceObject $fileArray -DifferenceObject $dictionaryArray |
    Where-Object {$_.SideIndicator -eq '<='} |
    ForEach-Object {Write-Output $_.InputObject}

只需运行Compare-Object -ReferenceObject $fileArray -DifferenceObject $dictionaryArray,我就会得到输出

InputObject                                          SideIndicator
@{PC=Joe; File=nopethere}                            &lt;=
@{PC=Joe; File=hi!!!@}                               &lt;=                                              

fileArray中的项目比此更多。当我运行$fileArray时,我得到

PC             File
Eric           I like to
Eric           there
Joe            code because
Joe            hello
Joe            but why?
Joe            *no\thank/ you :c
Joe            nopethere
Joe            hi!!!@

为什么我的代码没有比较这些对象中的每一个?

编辑

这是dictionary.txt

Eric
because
hello there

Joe
but why?
*no\thank/ you :c
nope

这是file.txt

Eric
I like to
there

Joe
code because
hello
but why?
*no\thank/ you :c
nopethere
hi!!!@

我使用循环创建对象。每个段落的第一行是每个后续对象的“ PC”。然后,每一行是每个对象的“文件”。我想检查哪些对象在fileArray中,而不在dictionaryArray中。我希望输出是

PC             File
Eric           I like to
Joe            code because
Joe            hello
Joe            nopethere
Joe            hi!!!@

任何帮助将不胜感激!

0 个答案:

没有答案