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
3
  • you're calling $guid = get-mailbox [email protected] ... at the top but then in your loop you're querying, presumably, the same mailbox again Get-mailbox $g.alias..., why? Commented Sep 26, 2022 at 22:24
  • updated to use CSV file Commented Sep 26, 2022 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 Commented Sep 26, 2022 at 22:34

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.