Author Posts

April 15, 2016 at 10:59 am

I have two CSV documents. One I have key names and a number given to them the other has key names in but the order is different with no number assigned. I need to assign the numbers to the second document based on what's in the first

csv1
KEY,Number
1935,3
23,4
55555,2
6666,1
99999999,8
V-23333,3

CS2
KEY,Number
55555,
23,
6666,
V-23333,
99999999,

Output should be
KEY,Number
55555,2
23,4
6666,1
V-23333,3
99999999,8

I actually get
KEY,Number
55555,NA
23,NA
6666,NA
V-23333,NA
99999999,NA

My code is
$KeyList = Import-Csv -Path "file1.csv"
$Numbers = Import-Csv -Path "file2.csv"
$AssignedNumbers = @()

ForEach ($key in $KeyList)
{

$Keymatch = $Numbers | where {$_.KEY -match $key.KEY}

If($userMatch)
{
$AssignedNumbers += New-Object PsObject -Property @{KEY =$key.KEY;Number =$Keymatch.Number}
}

else
{
$AssignedNumbers += New-Object PsObject -Property @{Vkey =$key.KEY;Number ="NA"}
}
}
$AssignedNumbers | export-csv "file3" -NoType

April 15, 2016 at 11:43 am

$file1 = Import-Csv -Path \\path\to\csv1
$file2 = Import-Csv -Path \\path\to\csv2

$file1 | ForEach-Object {
If ($file2.key -contains $_.key){
    [PSCustomObject]@{
        Key = $_.key
        Number = $_.number
        }}
} | Export-Csv .\file3.csv -NoTypeInformation