Question Récupération de données dans deux CSV

Plus d'informations
il y a 1 an 1 semaine #33112 par Fontaine
Bonjour à tous,

Jusque là j'ai déjà eu à faire à la manipulation de CSV uniquement dans le contexte d'importer des éléments et de les réinjecter dans l'AD par exemple.

Une collaboratrice m'a sollicité pour  une nouvelle problématique et j'avoue ne pas savoir comment prendre le problème.

Je dispose de deux fichiers CSV.

Le premier contient les colonnes et les informations suivantes:

identifiant | information1

Le second :

identifiant | information2

Le souhait de ma collaboratrice est de fusionner les informations dans un nouveau CSV du type

identifiant | information1 | information2

De tel sorte que l'identifiant existant dans les deux csv soit repris avec les informations de tel et tel fichier.

J'ai tenté de trouver des exemples sans succès alors en réfléchissant je suppose qu' après avoir importer les deux csv je dois réaliser une boucle For et me baser sur l'identifiant mais je reste perdu sur la logique de la construction de cette boucle .

Si une âme charitable pouvait me guider ou m'orienter, je lui en serais reconnaissant.

Merci par avance et belle journée

Connexion ou Créer un compte pour participer à la conversation.

Plus d'informations
il y a 1 an 4 jours #33115 par ericlm128
Voici quelques idées.
La méthode 1 est optimisé pour les plus gros traitement avec une table de hachage

csv1.txt
identifiant,information1
id1,i1_1
id2,i1_2
id3,i1_3

csv2.txt
identifiant,information2
id1,i2_1
id2,i2_2
id4,i2_4

Script
$csv1 = Import-Csv -LiteralPath ".\csv1.txt"
$csv2 = Import-Csv -LiteralPath ".\csv2.txt"


# Méthode 1
$hash = @{}
$csv1 | ForEach-Object {
    $hash.Add($_.identifiant, [PSCustomObject]@{
        identifiant = $_.identifiant
        information1 = $_.information1
        information2 = ""
    })
}

$csv2 | ForEach-Object {
    if ($hash.ContainsKey($_.identifiant))
    {
        $hash[$_.identifiant].information2 = $_.information2
    }
    else
    {
        $hash.Add($_.identifiant, [PSCustomObject]@{
            identifiant = $_.identifiant
            information1 = ""
            information2 = $_.information2
        })
    }
}

$result = $hash.Values | Sort-Object identifiant


# Méthode 2
$result = @($csv1, $csv2).identifiant |
Sort-Object -Unique |
Select-Object @{Name = 'identifiant'; Expression = {$_}}, @{Name = 'information1'; Expression = {
    $pipe = $_
    $csv1 | Where-Object {$_.identifiant -eq $pipe} | Select-Object -ExpandProperty information1 -First 1
}}, @{Name = 'information2'; Expression = {
    $pipe = $_
    $csv2 | Where-Object {$_.identifiant -eq $pipe} | Select-Object -ExpandProperty information2 -First 1
}}

$result

Connexion ou Créer un compte pour participer à la conversation.

Plus d'informations
il y a 1 an 1 jour - il y a 1 an 1 jour #33117 par Fontaine
Bonjour Eric,

Merci beaucoup pour votre aide, j'étais bien mal parti dans mes recherches !
Je me suis appuyé sur votre seconde proposition et cela correspond pleinement à nos besoins.

Si je peux user de votre gentillesse, j'aurais besoin d'intégrer une donnée supplémentaire du csv1

csv1.txt
identifiant,information1,information2
id1,i1_1,i2_1
id2,i1_2,i2_2
id3,i1_3,i2_3

csv2.txt
identifiant,information3
id1,i3_1
id2,i3_2
id4,i3_4

pour un résultat de cette forme
identifiant | information1 | information2 |information3

Comment intégrer information2 dans la table de hachage pour une prise en compte dans le résultat ?

J'ai tenté de manipuler les "Select-Object" pour l'y intégrer mais forcé de constater que cela me dépasse ...
Dernière édition: il y a 1 an 1 jour par Fontaine.

Connexion ou Créer un compte pour participer à la conversation.

Plus d'informations
il y a 1 an 1 jour #33118 par ericlm128
Je dirais comme cela
$csv1 = Import-Csv -LiteralPath ".\csv1.txt"
$csv2 = Import-Csv -LiteralPath ".\csv2.txt"


# Méthode 1
$hash = @{}
$csv1 | ForEach-Object {
    $hash.Add($_.identifiant, [PSCustomObject]@{
        identifiant = $_.identifiant
        information1 = $_.information1
        information2 = $_.information2
    })
}

$csv2 | ForEach-Object {
    if ($hash.ContainsKey($_.identifiant))
    {
        $hash[$_.identifiant].information3 = $_.information3
    }
    else
    {
        $hash.Add($_.identifiant, [PSCustomObject]@{
            identifiant = $_.identifiant
            information1 = ""
            information2 = ""
            information3 = $_.information3
        })
    }
}

$result = $hash.Values | Sort-Object identifiant

Connexion ou Créer un compte pour participer à la conversation.

Plus d'informations
il y a 1 an 23 heures - il y a 1 an 23 heures #33119 par Fontaine
 

Fichier attaché :

Nom du fichier : data.csv.txt
Taille du ficher :0 ko
 

Fichier attaché :

Nom du fichier : codeanaly.csv.txt
Taille du ficher :0 ko
 

Je viens de tester cette méthode une et ce n'est pas probant (voir pj)


Voilà comme je l'ai traduis:

$csv1 = Import-CSV -Path D:\Scripts\AD\CCE\Fic\codeanaly.csv -Delimiter ";" -Encoding UTF8
$csv2 = Import-CSV -Path D:\Scripts\AD\CCE\Rapport\data.csv -Delimiter "," -Encoding UTF8
$hash = @{}
$csv1 | ForEach-Object {
    $hash.Add($_.identifiant, [PSCustomObject]@{
        Identifiant = $_.identifiant
        Nom = $_.Name
        CodeAnalytique = $_.cramCodeComptaAnalytique
    })
}

$csv2 | ForEach-Object {
    if ($hash.ContainsKey($_.identifiant))
    {
        $hash[$_.identifiant].Impression = $_.Impression
    }
    else
    {
        $hash.Add($_.identifiant, [PSCustomObject]@{
            Identifiant = $_.identifiant
            Nom = ""
            CodeAnalytique = ""
            Impression = $_.Impression
        })
    }
}

$result = $hash.Values | Sort-Object Identifiant


J'ai joint les deux csv que je dois traité pour illustrer et que ce soit plus parlant.
Pièces jointes :
Dernière édition: il y a 1 an 23 heures par Fontaine.

Connexion ou Créer un compte pour participer à la conversation.

Plus d'informations
il y a 1 an 21 heures - il y a 1 an 21 heures #33120 par ericlm128
Re, je comprend que ma méthode sois un peu "spécifique" nous allons la généralisé pour plus de flexibilité et simplicité de réutilisation

$csv1 = Import-CSV -Path .\codeanaly.csv -Delimiter ";" -Encoding UTF8
$csv2 = Import-CSV -Path .\data.csv -Delimiter "," -Encoding UTF8

function Join-Datas($ColumnJoin)
{
    begin
    {
        $hash = @{}
        $datas = @()
        $TemplateObject = New-Object -TypeName PsObject -Property @{}
    }
 
    process
    {
        $datas += $_
    }

    end
    {
        $propertys = ($datas | ForEach-Object {$_ | Get-member -MemberType 'NoteProperty' | Select-Object -ExpandProperty 'Name'} | Select-Object -Unique)
        foreach ($property in $propertys)
        {
            $TemplateObject | Add-Member -MemberType NoteProperty -Name $property -Value $null
        }

        foreach($data in $datas)
        {
            if ($hash.ContainsKey($data.PsObject.Properties.Item($ColumnJoin).Value))
            {
                $obj = $hash[$data.PsObject.Properties.Item($ColumnJoin).Value]
            }
            else
            {
                $obj = $TemplateObject.PsObject.Copy()
                $hash[$data.PsObject.Properties.Item($ColumnJoin).Value] = $obj
            }

            $data.PsObject.Properties | ForEach-Object {$obj.PsObject.Properties.Item($_.Name).Value = $_.Value}
        }
        
        $hash.Values
    }
}

$csv1, $csv2 | Join-Datas -ColumnJoin "identifiant" | Export-Csv -Path ".\out.csv" -Encoding UTF8 -NoTypeInformation -Force
Dernière édition: il y a 1 an 21 heures par ericlm128.

Connexion ou Créer un compte pour participer à la conversation.

Temps de génération de la page : 0.101 secondes
Propulsé par Kunena