1

I am appending strings to an array so I can later output that array to a file, but after each new append, the 1st character is a space. I do not want that space, how do I remove it?

Here is my code sample:

$store += @('sample' + "`r`n")
$store += @('other' + "`r`n")
$store += @('new')

write-host $store

This outputs

sample
 other
 new
arealhobo
  • 447
  • 1
  • 6
  • 17

2 Answers2

1

There are no spaces in your array, this is just how it is being displayed by Write-Host:

$store = @('sample')
$store += @('other')
$store += @('new')

write-host $store

Displays:

sample other new

See also: How can I remove spaces from this PowerShell array?

Besides, the default output (Write-Output) usually adds new lines (compliant with the current system):

$store

Displays:

sample
other
new

As also cmdlets like Add-Content do:

$store | Add-Content .\MyFile.txt

Meaning that you probably also don't want to fabricate your own new lines ("`r`n") in your arrays items. see also: What's the difference between “Write-Host”, “Write-Output”, or “[console]::WriteLine”?

Bottom line: There shouldn't be any need to add or remove separators (spaces or new lines) to your array items because separators do not take part of the array itself but only during the output where the items usually being joined

 

$Store = @(
    'sample'
    'other'
    'new'
)
iRon
  • 20,463
  • 10
  • 53
  • 79
0

Alternatively, you can use ArrayList when you want to add new items.

$store = @("sample","other","new")

# Define your ArrayList
$store = New-Object System.Collections.ArrayList(,$store)
...
...
$store.Add("newItem1") | Out-Null
...
...
$store.Add("newItem2") | Out-Null

We are piping to Out-Null in order to suppress the Index of added items being written to the host.

Hope this helps.

Karthick Ganesan
  • 375
  • 4
  • 11