0

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
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
Chabango
  • 111
  • 8
  • you're calling `$guid = get-mailbox YuTe.Wu@fda.hhs.gov ...` at the top but then in your loop you're querying, _presumably_, the same mailbox again `Get-mailbox $g.alias...`, why? – Santiago Squarzon Sep 26 '22 at 22:24
  • updated to use CSV file – Chabango Sep 26 '22 at 22:30
  • 1
    all your array elements are a reference of the same object, that's the issue. you need to instantiate a new object per loop iteration instead of updating the same object over and over – Santiago Squarzon Sep 26 '22 at 22:34

2 Answers2

2

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
Santiago Squarzon
  • 41,465
  • 5
  • 14
  • 37
0

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
mjsqu
  • 5,151
  • 1
  • 17
  • 21