Powershell将csv列值拆分为两个单独的列值

时间:2016-01-20 18:11:01

标签: powershell powershell-v3.0

假设我有一个包含5条记录的csv文件(实际上它大约是80,000条)。

Csv文件:

column1,columnICareAbout,column2
someRandomValue,John Doe - Generic,someRandomValue
someRandomValue,Captain Teemo - pocketPet,someRandomValue
someRandomValue,Pinky Brain - Fictional,someRandomValue
someRandomValue,Miyamoto Musashi - swordsman,someRandomValue
someRandomValue,Kato yasunori - troubleMaker - Extreme,someRandomValue

给出以下代码:

注意:我知道数组值是正确的,我只需要知道如何遍历表达式中的数组。

$firstNames = @()
$firstNameCounter = 0
$lastNames = @()
$lastNameCounter = 0

Import-Csv $file1 | 
    foreach { 
        $firstNames += $_.Description.split(" ")[0]
        $lastNames += $_.Description.split(" ")[1]
    }

Import-Csv $file1 |
    Select-Object  *, @{n='First Name'; e={$firstNames[$firstNameCounter];$script:firstNameCounter++}}, @{n='Last Name'; e={$lastNames[$lastNameCounter];$script:lastNameCounter++}} | 
    Export-Csv "testresults.csv" -NoTypeInformation -Force

我每次只获得数组中的第一个元素。所以最终结果文件看起来像这样

column1,columnICareAbout,column2,First Name,Last Name
someRandomValue,John Doe - Generic,someRandomValue,John,Doe
someRandomValue,Captain Teemo - pocketPet,someRandomValue,John,Doe
someRandomValue,Pinky Brain - Fictional,someRandomValue,John,Doe
someRandomValue,Miyamoto Musashi - swordsman,someRandomValue,John,Doe
someRandomValue,Kato yasunori - troubleMaker - Extreme,someRandomValue,John,Doe

我希望文件看起来像这样

column1,columnICareAbout,column2,First Name,Last Name
someRandomValue,John Doe - Generic,someRandomValue,John,Doe
someRandomValue,Captain Teemo - pocketPet,someRandomValue,Captain,Teemo
someRandomValue,Pinky Brain - Fictional,someRandomValue,Pinky,Brain
someRandomValue,Miyamoto Musashi - swordsman,someRandomValue,Miyamoto,Musashi
someRandomValue,Kato yasunori - troubleMaker - Extreme,someRandomValue,Kato,yasunori

有谁能告诉我我做错了什么?

1 个答案:

答案 0 :(得分:1)

Import-Csv $file1 | 
foreach { 
    $firstName = $_.Description.split(" ")[0]
    $lastName = $_.Description.split(" ")[1]

    $_ | Add-Member -MemberType NoteProperty -Name FirstName -Value $firstName
    $_ | Add-Member -MemberType NoteProperty -Name LastName -Value $lastName
} | Export-Csv 'results.csv'

Add-Member命令将追加2列FirstName和LastName