Add content to CSV-file if match exist

Ahoy!

This is kinda like a continuation of my old problem (https://powershell.org/forums/topic/add-content-from-txt-to-a-csv-file/).

I have 2 csv-files, and I want to add a new column, named “KAP” with the value “X” if the name/user exist in both files.

Example of the files:

file.csv

"DisplayName","PrimarySmtpAddress","WhenMailboxCreated","IssueWarningQuota","Total Size (MB)"
"gemensam","gemensam@xyxy.se","2012-12-18 19:38:31","3.809 GB (4,089,446,400 bytes)","4"
"Göran Göransson","göran@xyxy.se","2012-12-18 18:52:32","3.809 GB (4,089,446,400 bytes)","974"
"Lars Snabelsson","lars@xyxy.se","2012-12-18 18:52:07","7.813 GB (8,388,608,000 bytes)","4451"
ad.csv

"name","whencreated"
"Göran Göransson","2008-12-18 16:09:38"
"Lars Snabelsson","2013-04-15 07:13:14"

This is how far I manage to come so far. But the code adds “KAP” with the value “X” to every row, even for "gemensam if the examples-files above would be used.

$userData2 = Import-Csv E:\file.csv
$appendData2 = Import-Csv E:\ad.csv
$userData2 | Foreach {
	$userName = $userData2.DisplayName
	$appendData2 | Foreach {
	$appendName = $appendData2.name
		if ($userName -like $appendName) 
	{
		$dataToAppend2 = $appendData2 | Where name -eq $_.DisplayName
    	Add-Member -InputObject $_ -MemberType NoteProperty -Name 'KAP' -Value "X"
   		Write-Output $_
	}
		else
		{
		}
	}
} | Export-Csv E:\kep_kap.csv -NoTypeInformation

Thanks in advance! And please tell me if you need more explanation.

Update: I’ve made some progress, posting the code within 1 hour.

Okey, any ideas why this doesn’t work?

EDIT: Simplified code:

$userData2 = Import-Csv E:\file.csv
$appendData2 = Import-Csv E:\ad.csv
$userNameNr = -1
$appendNameNr = -1

$userNames = $userData2.DisplayName
$userNames | Foreach {

$userNameNr += 1
$userName = $userNames[$userNameNr]
$appendNames = $appendData2.name
$appendNames | Foreach {
		$appendNameNr += 1
		$appendName = $appendNames[$appendNameNr]
		if ($userName -like $appendName) 
			{
				echo "Hit! $appendName is in both files."
			}
		else
		{
			#echo "Miss"
		}
	}

}

I keep talking to myself :smiley: … I just found how to solve the problem:

$userData2 = Import-Csv E:\Simon\file.csv $appendData2 = Import-Csv E:\Simon\ad.csv $userNameNr = -1 $userNames = $userData2.DisplayName $appendNames = $appendData2.name $appendNameNr = $appendNames.Count
$userNames | Foreach {
$appendNameNr = $appendNames.Count
$userNameNr += 1
$userName = $userNames[$userNameNr]

$appendNames | Foreach {
		$appendNameNr += -1
		$appendName = $appendNames[$appendNameNr]
		if ($userName -like $appendName) 
			{
				Write-Host "Hit!! $appendName exists in both files."
			}
		else
		{
			#echo "Miss"
		}
	}

}

Now I just need to merge it to a new file with the information from file.csv…