Forum Discussion
kjetilj
Jul 16, 2021Copper Contributor
Importing CSV, splitting names and joining
Hi, Very new to PowerShell and scripting so I'm trying to do a lab exercise. I'm trying to take input from a CSV file where the name is formatted as "Surname, Name". When I split this it returns...
- Jul 16, 2021
Here is a possible solutions
$Users = Import-Csv -Path "C:\Users\user\Scripts\Labs\StuffForLabs\UserListB.csv" -Delimiter ";" | ForEach-Object { ($_.Name -split ', ') } for ($i=0; $i -le ($users.count-1); $i=$i+2 ){ $Users[$i+1] + " " + $Users[$i] }
this is the output
Dorthy Rhodes Chauncey Woodward Julian Horn
psophos
Jul 16, 2021Brass Contributor
Another way to approach it:
$Users = Import-Csv -Path "C:\Users\user\Scripts\Labs\StuffForLabs\UserListB.csv" -Delimiter ";"
foreach ($user in $Users)
{
$name = "{1} {0}" -f ($user -split ', ')
$name
}
Might be a little easier to understand.
Though I have complicated it with the way I have used the -f format string.
gastone
Jul 17, 2021Brass Contributor
psophosNice the idea to use -f but your code is wrong, not really, the worng part is that kjetilj
using
Import-Csv -Path "C:\Users\user\Scripts\Labs\StuffForLabs\UserListB.csv" -Delimiter ";"
for reading a non csv file and the non present delimiter ";" is necessary to correct the starting point error.
This is not a CSV!
Name
Rhodes, Dorthy
Woodward, Chauncey
Horn, Julian
psophosThis the correct code
cls
"The corrected script, for the non CSV..."
$Users = Import-Csv -Path "C:\Users\user\Scripts\Labs\StuffForLabs\UserListB.csv" -Delimiter ";"
foreach ($user in $Users)
{
$name = "{1} {0}" -f ($user.name -split ',')
$name
}
A more readable code with some comment
#
# skip the first line, so we have a regular csv
$reallyAcsv=Get-Content -Path "C:\Users\user\Scripts\Labs\StuffForLabs\UserListB.csv" | Select-Object -Skip 1
# Add header for readability
$USRs=$reallyAcsv | ConvertFrom-Csv -Header 'surname','name'
# Now is easy to understand...
$USRs|foreach-object {"$($_.name) $($_.surname)"}
# if you want only name...
$USRs|foreach-object {$_.name)}
# if you want only surname...
$USRs|foreach-object {$_.surname)}
The same code in a single line
"+ In a single line +"
Get-Content -Path "C:\Users\user\Scripts\Labs\StuffForLabs\UserListB.csv" |
Select-Object -Skip 1 |
ConvertFrom-Csv -Header 'surname','name' |
foreach-object {"$($_.name) $($_.surname)"}
I hope now is more clear the different solutions
Bye Gas