0
可以說我有一個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
誰能告訴我什麼,我做錯了什麼?
爲什麼在兩個步驟做呢? 'Import-CSV $ File1 |選擇*,@ {l ='First Name'; e = {$ _。Description .Split('')[0]}},@ {l ='Last Name'; e = {$ _。Description.Split '')[1]}} | Export-CSV testresults.csv -NoType -Force' – TheMadTechnician
與第二個循環不同,只需在第一個循環中追加屬性即可。添加成員-MemberType NoteProperty - 名字 - 值$ firstName' – skukx
感謝TheMadTechnician。這工作。儘管我仍然想知道如何在表達式中遍歷數組。這會幫助我解決目前我正面臨的一個問題。 –