Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Basic concatenation in Powershell doesn't work

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

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

@() 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
}
$filepaths

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)
}
$filepaths

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading