1

I'm currently trying to write an entire write to a line of a file, not new lines in powershell. I add items to the array using $array += $newitem (which works), yet when it adds the full array to the file (I've tried both streamwriter and out-file with append), it adds each item as a new line.

Pseudocode:

First round 1 then 2 then 3 are added to $array. Second round, which starts $array back at an empty state, 4 then 5 then 6 are added to $array. Then I output the data. The result in a file:

1,
2,
3
4,
5,
6

The output I want:

1,2,3
4,5,6
1
  • This sounds like an X-Y Problem. Please take a step back and describe the actual problem you're trying to solve instead of what you perceive as the solution. Commented Jun 24, 2014 at 17:57

2 Answers 2

1

What about using the -join operator? Assuming your first array has 1,2,3 added to it:

$array = ("1","2","3")
$array -join ','

What that does is take each element, and slaps the ',' character in between them. You can store the result of the $array -join ',' into another variable, then output it later if you need to. That would look like this:

$foo = $array -join ','

// do a bunch of stuff

// output $foo here to the command line, or do whatever else with it\

$foo

Sign up to request clarification or add additional context in comments.

Comments

0

It really sounds like you shouldn't be using an array from the way you describe things. What you may want to try instead is to use a string instead like:

[string]$Line="$Line,$NewItem"

As a string it will just add the comma and the new item to the end of the string.

Are you trying to manually build a CSV or something? There may be better ways to go about what you are doing.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.