1

I'm looping through some files and want to prepend the filename to an existing file. I thought I'd got stuff going ok, but by the second time around the loop, I lose the existing end of the file, and get System.Object[] instead of the former contents.

A simple example here shows roughly what I'm doing to prepend the information, and replicates the outcome (which I don't want!).

$a = "1","2","3"
$b = "test"
$c = -join $b,$a
# At this point, $c is as I expect; it has added $b to the start of the list.
$a = $c
$c = -join $b,$a
# This time, when I try to add $b to the front of $a, it correctly adds the new line, and the second line is also correct, but then it dumps the object properties of the remaining lines (or something?)

The output is shown below

 test
 test


Length         : 3
LongLength     : 3
Rank           : 1
SyncRoot       : {1, 2, 3}
IsReadOnly     : False
IsFixedSize    : True
IsSynchronized : False
Count          : 3

If you're writing this to a file using set-content, then it writes the object properties as System.Object[], which isn't what I want!

Thanks

Update: As per the comment on this original post, the solution I'm looking for is to use $a = (,$b)+$a. This has the effect of prepending the string in $b to the start of the array of strings stored in $a.

3
  • Unary -join is string concatenation operator. Unary -join have higher precedence than binary comma. Thus -join $b,$a is (-join $b),$a. Commented Jan 10, 2017 at 11:52
  • 1
    P.S. (,$b)+$a Commented Jan 10, 2017 at 11:59
  • Dude your (,$b)+$a works... why don't you write is as an answer? Commented Jan 10, 2017 at 12:10

1 Answer 1

2

I think, you need some clarification here:

$a = "1","2","3"
$b = "test"
$c = -join $b,$a

does not create an array $c containing

'test', '1', '2', '3'

instead $clooks like this:

'test', ('1', '2', '3')

What I think you wanted to do is:

$c = $b , $a

which results in

'test', '1', '2', '3'
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you for your reply. I went away from using + for the strings because it doesn't do what I want. I need the output to be "test";"1";"2";"3" (where ; represents a new line), but instead it outputs test1 2 3
Well I didn't realise you could use a comma as well! There's about 15 ways to join strings, it seems. Unfortunately your method doesn't work for this problem. Please try the following (where ; is a line break): $a = "1","2","3"; $b = "test"; $a = $b,$a; $a = $b,$a; #You will see that $a contains Object Properties
That is an display issue from powershell itself.
The question is now more: What do you want to do? Would you update your question with that info?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.