首页 > 解决方案 > 比较两个 CSV 文件并使用不匹配的值创建一个新文件

问题描述

我在 CSV 中有两个文件,ServiceAccount 文件,ServiceAccount - 排除

ServiceAccount File Details

FirstName Surname   LoginName
Andrew    Jones     AJones
Ajay      Singh     ASingh
Bobby     Deol      BDeol
Rony      Choudhury RChoudhury
Tim       Perera    TPerera

ServiceAccount - 排除

FirstName Surname   LoginName
Andrew    Jones     AJones
Bobby     Deol      BDeol

新的 CSV 文件应如下所示

FirstName Surname   LoginName
Ajay      Singh     ASingh
Rony      Choudhury RChoudhury
Tim       Perera    TPerera

我已经写了这段代码,但是我看不到上面的结果,谁能在这里帮忙,下面是我的代码。

$Path = "C:\PowerShell"


$ServiceAccountExclusion = "C:\temp\Test\ServiceAccount - Exclusion.csv"
$ServcieAccount = "C:\temp\Test\ServiceAccount.csv"
$UserList = Import-Csv $ServiceAccountExclusion -Delimiter ","
$UserData = Import-Csv $ServcieAccount -Delimiter ","

$UserOutput = @()

    ForEach ($name in $UserData)
    {

        $userMatch = $UserList | where {$_.FirstName -ne $name.FirstName}
        If($userMatch)
        {
            # Process the data

            $UserOutput += New-Object PsObject -Property @{UserName =$name.FirstName}

        }
        
        <# {
            $UserOutput += New-Object PsObject -Property @{UserName =$name.FirstName}
        }  #>
    }
$UserOutput | ft

标签: powershellpowershell-4.0

解决方案


这完全取决于您是否正在寻找解决问题的结果,或者您是否正在寻找在 PowerShell 中解决此问题的绝对最佳答案。

就我而言,我可以为您提供一个快速而肮脏的解决方案,从对象到字符串,然后在需要时再返回

(Get-Content 'C:\PS\ServiceAccounts.csv') + (Get-Content 'C:\PS\ServiceAccountsExcluded.csv') | select -Unique | Out-File -FilePath "C:\PS\ServiceAccountsCombined.csv"

$ServiceAccountsCombined = Import-CSV -Path "C:\PS\ServiceAccountsCombined.csv"

$ServiceAccountsCombined

推荐阅读