Joseph
Joseph

Reputation: 661

Why are the indices of the arraylist added to the arraylist itself?

I'm writing a script that dynamically generates to the screen a list of AD sites that happen to contain Exchange servers (specifically, using Get-ExchangeServer | % {Get-ADSite $_.Site} | Sort -Unique) and that part works well enough when I generate that list like so:

function SiteChoiceMenu {
$sites = Get-ExchangeServer | % {Get-ADSite $_.Site} | Sort -Unique
$siteCount = $sites.count
$bullets = New-Object -TypeName System.Collections.ArrayList($null)

for ($i=0;$i -lt $siteCount;$i++) {
    $index = $i+1
    $bullet = "$index. " + $sites[$i].Name
    $bullets.Add($bullet)
}
foreach ($bullet in $bullets) {Write-Host $bullet}
$siteChoice = Read-Host "Enter choice"

if ($siteChoice -in 1..$siteCount) { $siteChosen = $sites[$siteChoice-1]; return $siteChosen }
}

$siteChosen

When I run this code, I have 5 sites that have Exchange servers, so it generates a list like this:

1. Site 1
2. Site 2

and so forth. When I write $siteChosen to the screen, the output looks like this:

0
1
2
3
4
5

Name                  HubSiteEnabled
Site1                 False

When I step into the code, I can see that "siteChosen" is set to the exact output above. When I look at my Arraylist, $bullets, it shows only the strings I expect it to show. Now, what I did try is using a normal array instead of an ArrayList collection object, it does not exhibit the behavior above. When I write out $siteChosen to the screen, it has just the site in it. Any ideas why?

Upvotes: 0

Views: 43

Answers (1)

veefu
veefu

Reputation: 2890

$bullets.Add($bullet) returns the the index at which the object was added in the ArrayList. Because you don't store it in a variable, the returned int is accumulated in the pipeline.

$thorwaway = $bullets.Add($bullet) will hide it.

This is just one of those things you have to watch out for when using .NET objects and methods.

Upvotes: 1

Related Questions