Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String concatenation with newline not working as expected

Tags:

powershell

I want to add a line break without adding a whole 'nother line to do so, here be my code:

"-- MANIFEST COUNT -- " >> "C:\psTest\test1.txt"
$manCount = (Get-ChildItem -filter "*manifest.csv").Count 
$manCount + " `n" >> "C:\psTest\test1.txt"

I thought that + " `n" would tack a line break onto the count, but it's not doing anything. I tried also + "`r`n" (I found this suggestion elsewhere on SO) but to no avail.

like image 337
n8. Avatar asked Dec 13 '25 13:12

n8.


2 Answers

Let me complement your own solution with an explanation:

Because $manCount, the LHS, is of type [int],

$manCount + " `n"

is effectively the same as:

$manCount + [int] " `n".Trim()

or:

$manCount + [int] ""

which is effectively the same as:

$manCount + 0

and therefore a no-op.

In PowerShell, the type of the LHS of an expression typically[1] determines what type the RHS will be coerced to, if necessary.

Therefore, by casting $manCount to [string], + then performs string concatenation, as you intended.

As Matt points out in a comment on your answer, you can also use string interpolation:

"$manCount `n"

[1]There are exceptions; e.g., '3' - '1' yields [int] 2; i.e., PowerShell treats both operands as numbers, because operator - has no meaning in a string context.

like image 137
mklement0 Avatar answered Dec 15 '25 03:12

mklement0


The integer needed to be cast as a string in order for the concatenation to take:

"-- MANIFEST COUNT -- " >> "C:\psTest\test1.txt"
$manCount = (Get-ChildItem -filter "*manifest.csv").Count 
[string]$manCount + "`r`n" >> "C:\psTest\test1.txt"
like image 28
n8. Avatar answered Dec 15 '25 04:12

n8.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!