Home > Enterprise >  Array in a foreach loop
Array in a foreach loop

Time:09-27

What am I doing wrong here?

The mailbox has an active an inactive mailbox so it will return two mailboxes. However, when trying to capture the output, I am only getting the last account in the array Note, this is a simplified version of a larger script, but kept it simple for this example.

        $guid = import-csv "c:\temp\Mailboxes.csv"

$DAta = New-Object psobject
$Data | Add-Member -MemberType NoteProperty -Name alias -Value $null
$Data | Add-Member -MemberType NoteProperty -Name guid -Value $null

$mbxcol = @()

#$data = $null

foreach ($G in $Guid){

$mbx = Get-mailbox $g.alias -IncludeInactiveMailbox



$data.alias = $mbx.alias
$data.guid = $mbx.guid

$MBXCol  = $Data


}

$mbxcol

CodePudding user response:

As explained in comments, every array element is a reference of the same object ($Data), a simple way to demonstrate using Object.ReferenceEquals Mehod with this example:

foreach ($item in 0..10) {
    $data.Alias = 'mailbox{0}' -f $item
    $data.Guid  = [guid]::NewGuid()
    $mbxcol     = $data
}

[object]::ReferenceEquals($data, $mbxcol[0]) # -> True

As for how to simplify and make your code more efficient, do not add elements ( =) to a fixed collection (@( )):

$result = (Import-Csv "c:\temp\Mailboxes.csv").Alias |
    Get-Mailbox -IncludeInactiveMailbox |
        Select-Object Alias, Guid

CodePudding user response:

A much more simple example of your code is:

$guid = ("A","B")

$Data = New-Object psobject
$Data | Add-Member -MemberType NoteProperty -Name alias -Value $null

$mbxcol = @()

foreach ($G in $Guid){

$mbx = $g

$data.alias = $mbx

$MBXCol  = $Data
}

$mbxcol

As @Santiago mentioned in his comment, $Data is a reference to an object, so each time you update it, you overwrite it, even if it is in an array. To fix this, instantiate the object each loop as follows:

$guid = ("A","B")

$mbxcol = @()

foreach ($G in $Guid){
$Data = New-Object psobject
$Data | Add-Member -MemberType NoteProperty -Name alias -Value $null

$mbx = $g

$data.alias = $mbx

$MBXCol  = $Data
}

$mbxcol
  • Related