从CSV输入创建自定义PowerShell对象

时间:2018-01-15 20:48:39

标签: powershell-v3.0

我有以下CSV输入:

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

我想将其转换为以下格式的字符串:

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' 
    } 
]

所以我想,我会首先构建一个自定义PS对象然后格式化它的输出。

$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

所以$newobject现在看起来像这样:

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}

下一步是构建一个对象数组或者哈希表,但我无法弄清楚如何,我有点迷失。你能指出我正确的方向吗?

1 个答案:

答案 0 :(得分:1)

使用calculated properties修改对象Import-Csv生成:

$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 

或者您也可以创建新的自定义对象:

$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
    }
}