'PowerShell append objects to variable list

Fairly new to PowerShell and wanting to learn how to append objects to a variable list. Below is the error message:

Method invocation failed because [System.IO.FileInfo] does not contain a method named 'op_Addition'.
At C:\Users\Username\Desktop\Sandbox\New folder\BoxProjectFiles.ps1:117 char:4
+             $MechDWGFile += $file
+             ~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (op_Addition:String) [], RuntimeException
    + FullyQualifiedErrorId : MethodNotFound

and code:

LogWrite "`n-------------Mechanical Drawing(s)------------"
foreach ($file in $MechDWGList)
{
    # Where the file name contains one of these filters
    foreach($filter in $MechDWGFilterList)
    {
        if($file.Name -like $filter)
        {
            $MechDWGFile += $file # this is where the error is happening, so I know it is probably something simple
            LogWrite $file.FullName
        }
    }
}

PowerShell 5.1 and Windows 10 OS is being used.

Could someone help me understand what's wrong with my syntax?



Solution 1:[1]

One big caveat about arrays in PowerShell—they are immutable.

Although you can "add" elements to an array in PowerShell using the overloaded += operator, what it essentially does is creates a new array with the elements of the first operand and the second operand combined.

This may be more of a personal preference, but when I plan on looping over a bunch of items to populate an array, I use an [ArrayList] instead.  ArrayLists are mutable by design.  Why this isn't the default in PowerShell, I have no idea.

Adding a new element to an existing array:

$Array1 = Get-ChildItem -Path 'C:\'
$Array2 = @()

# Add only the directories to our second array
foreach ($Item in $Array1) {
    if ($Item.PSIsContainer) {
        $Array2 += $Item    # This creates a new array every time
    }
}

$Array2

Adding a new element to an existing [ArrayList]:

$Array1 = Get-ChildItem -Path 'C:\'
$Array2 = [System.Collections.ArrayList]@()

# Add only the directories to our ArrayList
foreach ($Item in $Array1) {
    if ($Item.PSIsContainer) {
        $null = $Array2.Add($Item)    # This does not create a new object each time.

        # The $null= prepend is because [ArrayList].Add() will output the ID of the
        #   last element added, so we assign that to null, keeping our console clean.
    }
}

$Array2

Side note: Like Mathias has stated, your variable $MechDWGFile may not have been initialized as an array, which is why the += overload operator didn't work and instead threw an error.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Damian T.