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

问题描述:

可以说我有一个csv文件有5个记录(实际上大约有80,000个)。Powershell将csv列的值拆分为两个单独的列值

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

为什么在两个步骤做呢? 'Import-CSV $ File1 |选择*,@ {l ='First Name'; e = {$ _。Description .Split('')[0]}},@ {l ='Last Name'; e = {$ _。Description.Split '')[1]}} | Export-CSV testresults.csv -NoType -Force' – TheMadTechnician

+0

与第二个循环不同,只需在第一个循环中追加属性即可。添加成员-MemberType NoteProperty - 名字 - 值$ firstName' – skukx

+0

感谢TheMadTechnician。这工作。尽管我仍然想知道如何在表达式中遍历数组。这会帮助我解决目前我正面临的一个问题。 –

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' 

添加会员命令将追加2列名和姓