Basic concatenation in Powershell doesn't work

I cannot push to $filepaths, can’t see why :

$files= @('file1.text','file2.txt')
foreach ($file in $files) {
  $filepaths.add("c:\test\" + $file)

>Solution :

@() is a System.Array (a fixed collection), reading from Remarks on the .Add method from this Class:

Ordinarily, an IList.Add implementation adds a member to a collection. However, because arrays have a fixed size (the IsFixedSize property always returns true), this method always throws a NotSupportedException exception.

PowerShell offers us the ability to recreate the array with a new element using the += operator, however this is not recommended for reasons very well explained in this answer.

You can either assign to a variable the output of your enumeration:

$filepaths = foreach($file in 'file1.txt', 'file2.txt') {
    "c:\test\" + $file

In this example, PowerShell will dynamically assign the type for $filepaths, if 1 element is returned from the enumeration it would be string, for more than one it would become object[] (Array).

Or use a collection that allows adding new elements, such as ArrayList or List<T>:

$filepaths = [Collections.Generic.List[string]]::new()
foreach($file in 'file1.txt', 'file2.txt') {
    $filepaths.Add("c:\test\" + $file)

Here, $filepaths would always be of the type List`1.

Leave a Reply