Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
538 views
in Technique[技术] by (71.8m points)

Splitting values into two columns powershell csv file

I have a PowerShell script that creates a csv file and neatly separates all user input. I need the remaining output to be split across the two headers and I'm struggling to find out how. Tried lots of different code but had no luck.

$Devices = read-host -Prompt "Enter Full Device Name" | out-file 'C:UsersPublicDesktopDevices.csv' -Force
$Find = ", "
$Replace = "`n"
$Arrange = (Get-Content 'C:UsersPublicDesktopDevices.csv') -replace "$Find","$Replace" | Set-Content 'C:UsersPublicDesktopDevices.csv' -Force
$CSV = import-csv 'C:UsersPublicDesktopDevices.csv' -Header "Firstname","Lastname" 
$CSV | Export-Csv -NoTypeInformation 'C:UsersPublicDesktopDevices.csv' 
$import = Import-Csv 'C:UsersPublicDesktopDevices.csv'

This is the output I currently have in the CSV:
Output

This is the output I am after:
Final Output

Could almost do with a foreach loop as the first and last names are likely to change as these are inputted using a variable

any help is appreciated.

question from:https://stackoverflow.com/questions/65843939/splitting-values-into-two-columns-powershell-csv-file

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Export-Csv exports 1 column per distinct property of the input - so to get 2 columns, you need to pipe an object with 2 properties to Export-Csv.

# read device names, split into individual strings
$devices = Read-Host -Prompt "Enter Full Device Name(s)"
$devices = $devices -split ',s*' |ForEach-Object Trim

# now create one object per device name
$records = $devices |ForEach-Object {
  # start by splitting the string into 2 on the first `-`
  $FirstName,$LastName = $_ -split '-',2

  # now create the object
  [pscustomobject]@{
    FirstName = $FirstName
    LastName = $LastName
  }
}

# ... and finally, export to CSV
$records |Export-Csv 'C:UsersPublicDesktopDevices.csv' -NoTypeInformation

If you want to retain the - as part of the FirstName value, change this line:

$FirstName,$LastName = $_ -split '-',2

to:

$FirstName,$LastName = $_ -split '(?<=-)',2

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...