如何使用PowerShell比较文本文件和csv文件

2exbekwf  于 2023-04-03  发布在  Shell
关注(0)|答案(1)|浏览(164)

我有一个名为EmployeeID.txt的txt文件,它看起来像这样

Number      ID
32324       KLEON
23424       MKEOK

我有一个名为FullInventory.csv的CSV文件,它看起来像这样

Name     URL        UPN               Status
John    http://     KLEON@COM.COM     Yes

我试图比较这两个文件,并把2个不同的文件称为matchFound.csv和notFound.txt文件。
如果在FullInventory.csv中找到EmployeeID.txt中的ID,则输出带有FullInventory.csv中所有列的matchFound.csv
如果在FullInventory.csv中未找到EmployeeID.txt中的ID,则输出NotFound.txt和EmployeeId.txt中的数据

$ImportTXT = Import-CSV -path $Global:EmployeeID -Delimiter "`t"
$ImportFullInv = Import-CSV -Path $Global:FullInventory 

ForEach ($TxtLine in $ImportTXT) {
  $TxtID = $TxtLine.ID

  if ($null -eq $txtID -or $txtID -eq '') {
    Write-Host "ID is empty"
  }
  else {
    $array = @();

    ForEach ($CSVLine in $ImportFullInv) {
      $CSVUPN = $CSVLine.UPN
      $UPNSPLIT = $CSVUPN -split "@"
      $array += $UPNSPLIT[0]
    }

    if ($array -contains $TxtID) {
    // Something is not right here.
   
      $CSVLine |  Export-Csv -Path "C:\Users\Desktop\matchFound.csv" -append
    

  
    }
    else {
      $TxtLine | Out-File -FilePath  "C:\Users\Desktop\notFound.txt" -append

    }
  }
}

我现在的问题是matchFound.csv文件没有输出正确的数据。我认为它输出的是csv文件中的最后一列数据,而不是它匹配的数据。任何帮助或建议都将非常感谢。

92dk7w1h

92dk7w1h1#

这可以通过使用Group-Object -AsHashtable来实现,以允许快速查找,散列键将是从UPN列中提取的Name。除了将其导出到两个不同的文件之外,您还可以使用steppable pipeline而不是-Append

$map = Import-Csv $FullInventory -Delimiter "`t" |
    Group-Object { [mailaddress]::new($_.UPN).User } -AsHashTable -AsString

$pipeMatch = { Export-Csv 'C:\Users\Desktop\matchFound.csv' -NoTypeInformation }.GetSteppablePipeline()
$pipeMatch.Begin($true)

Import-Csv $EmployeeID -Delimiter "`t" | ForEach-Object {
    # if this ID exists in the full inventory
    if($map.ContainsKey($_.ID)) {
        # export all rows from inventory matching this ID
        $map[$_.ID] | ForEach-Object { $pipeMatch.Process($_) }
        # and go to the next ID
        return
    }

    # else, export this line to the not found csv
    $_
} | Export-Csv "C:\Users\Desktop\notFound.csv" -NoTypeInformation

$pipeMatch.End()

相关问题