2

I have the following CSV input:

id,name,surname,age,description
1,michael,jackson,50,desc1
2,james,hetfield,55,desc2

I want to convert it into the following format as a string:

availableValues = [ 
    { 
        'value' : 'id=1,name=michael,surname=jackson,age=50', 
        'displayName' : 'michael', 
        'description' : 'desc1' 
    }, 
    {
        'value' : 'id=1,name=james,surname=hetfield,age=55', 
        'displayName' : 'james', 
        'description' : 'desc2' 
    } 
]

So I thought, I would build a custom PS object first and then format its output.

$csvfile = "C:\Users\<blabla>\Desktop\scr\csv.txt"
$csv = Import-Csv $csvfile
$newobject = New-Object -TypeName PSOBject
Add-Member -NotePropertyName value -NotePropertyValue $csv -InputObject $newobject
Add-Member -NotePropertyName displayName -NotePropertyValue $csv.name -InputObject $newobject
Add-Member -NotePropertyName description -NotePropertyValue $csv.description -InputObject $newobject

So $newobject looks like this now:

PS> $newobject

value                                                                                                                                 displayName      description   
-----                                                                                                                                 -----------      -----------   
{@{id=1; name=michael; surname=jackson; age=50; description=desc1}, @{id=2; name=james; surname=hetfield; age=55; description=desc2}} {michael, james} {desc1, desc2}

The next step would be build an array of objects or maybe a hashtable but I could not figure it out how, I'm a bit lost. Could you point me into the right direction?

1 Answer 1

2

Use calculated properties to modify the objects Import-Csv produces:

$availableValues = Import-Csv $csvfile | Select-Object @{n='value';e={
    'id={0},name={1},surname={2},age={3}' -f $_.id, $_.name, $_.surname, $_.age
}}, @{n='displayName';e={$_.name}}, description 

Alternatively you could also create new custom objects:

$availableValues = Import-Csv $csvfile | ForEach-Object {
    [PSCustomObject]@{
        'value'       = 'id={0},name={1},surname={2},age={3}' -f $_.id, $_.name, $_.surname, $_.age
        'displayName' = $_.name
        'description' = $_.description
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.