Mark Minasi's Tech Forum
Sign up Calendar Latest Topics
 
 
 


Reply
  Author   Comment  
meloao

New Friend (or an Old Friend who Built a New Account)
Registered:
Posts: 97
Reply with quote  #1 
I have a CSV file that contains about 15 columns with data.  The columns are separated by a '|' delimiter.  I am trying to write a script to append data to it that is includes the delimiter. 

My script thus far uses Read-Host to get user input that will populate the spreadsheet. Note that of the 15 columns, only about 4 pieces of data are required and the rest could potentially be blank. 

All the input from Read-Host has been assigned to a variable.  Includes in the script is a line of code that populates a new array with the variables.

     $arrayUser = "$firstName", "$middleName", "$lastName", "$department", "$telephoneNumber", "$location"

Before the statement above,  I used import-csv to read the csv file, like so:

$csvSource = Import-Csv $PathAndFile -Delimiter $fileDelimiter -Header 'First_name', 'Middle_Name', 'Last_Name', 'Department'

I have the logic in my head just not sure how to make it happen.  I'm thinking I need to use a ForEach loop to process each item (using index e.g. - $arrayUser[0] ) and assign to to the column name.   Doing some reading it looks like I need to use Add-Content to append to existing CSV.   

0
meloao

New Friend (or an Old Friend who Built a New Account)
Registered:
Posts: 97
Reply with quote  #2 
Also I want to add a delimiter between each item in the array --- to mimic what's in the csv file. 
0
meloao

New Friend (or an Old Friend who Built a New Account)
Registered:
Posts: 97
Reply with quote  #3 
Another update.... so I used Add-Content -Path $PathAndFile -Value $arrayUser but it is putting each array element on a different line.
0
meloao

New Friend (or an Old Friend who Built a New Account)
Registered:
Posts: 97
Reply with quote  #4 
Another updated, I learned a new command  "-join"

so what I have now is $appendUser = $arrayUser -join "|"   --->  This does what I want it to do.  It puts a | in between each array element.  

Now when I run Add-Content -path $PathAndFile -Value $appendUser  it puts everything on a different line in the CSV..  I'm trying to get each array element to the same row. 
0
meloao

New Friend (or an Old Friend who Built a New Account)
Registered:
Posts: 97
Reply with quote  #5 
OK, I don't know what happened but the above works now! However I also did see that Add-Content also has a -NoNewLine parameter so I may include that anyway just to be on the safe side
0
Infradeploy

Avatar / Picture

Senior Member
Registered:
Posts: 171
Reply with quote  #6 
If you have an array: Export-csv -delim "|" -append
__________________
Have SpaceSuit, Will Travel

0
Previous Topic | Next Topic
Print
Reply

Quick Navigation:

Easily create a Forum Website with Website Toolbox.