PowerShell Parsing ArrayLists

Viewed 858

Problem

I am working on a script that utilizes several ArrayList objects and the contents of these objects gets placed through filters and the results are stored into temp ArrayLists. However, I am consistently running into a problem where I get excess data that I am not expecting and have no idea where it is coming from.

Example Object:

$installInfos = New-Object System.Collections.ArrayList
$InstallInfo = New-Object PSObject -Property @{
    SoftwareName = "Some Name"
    ServiceName = "Some Service"
    ProcessName = "Some Process"
    FileLocation = "Some Directory"
    StartupType = "Auto"
}
$installInfos.Add($installInfo)

The objects are stored into their own .psm1 file and are called like so:

Import-Module (Join-Path $PSScriptRoot ""InstallerInfo.psm1") -Force | Out-Null
$tempServicesList = ReturnAllData #This is a function inside the psm1 file that returns the $installInfos ArrayList

Next... Using a Form Checkbox, I parse the data once so that I only interact with the services the User selected as so:

$checkedServices = New-Object System.Collections.ArrayList

ForEach ($item in $SoftwareCheckboxes) {
    if ($item.Checked) {
        if (item.Text) {
            $checkedServices.Add($item.Text)
        }
    }
}

$selectedServices = New-Object System.Collections.ArrayList
ForEach ($service in $tempServicesList) {
    ForEach ($checkedService in $checkedServices) {
        If ($checkedService -eq $service.SoftwareName) {
            $selectedServices.Add($service)
        }
    }
}

Up to this point, everything is good. Even the contents are as expected... However, in the next part I cannot explain the disconnect that is happening.

I have most of the above in a single function getSelectedServices which ends with return $selectedService as the final line of the function. I then create a new object which calls upon that function to populate itself as so:

$selectedServicesList = getSelectedServices

However, I kept having issues... After several hours of debugging, I narrowed down to the culprit being what data was stored into $selectedServicesList . Instead of getting a new ArrayList Object containing only the Objects stored in $selectedServices , I get a series of digits taking up several of the beginning indexes. In some cases it's only up to index 15~16, in other cases it's up to index ~83. The values end up looking something like:

Index 78 = 37
Index 79 = 38
Index 80 = 39
Index 81 = 40
Index 82 = @{<#objects data#>}
Index 83 = @{<#objects data#>}
Index 84 = @{<#objects data#>}

Question

Does anyone know what is causing this and how I can fix it?

1 Answers

ArrayList.Add returns the index of the item added, and this goes into your output stream.

To prevent this side effect use this pattern:

$null = $checkedServices.Add($item.Text)
-or-
$checkedServices.Add($item.Text) | Out-Null
Related