powershellazure-active-directoryexchange-online

powershell storing multiple returns as unique variables


I have run into a nasty little issue I cannot figure out how to solve. When I run:

Get-Mailbox -softdeletedmailbox -identity blahblah@itsasecret.edu | fl *exchangeguid*

I get multiple results on multiple lines:

ExchangeGuid : aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa

ExchangeGuid : bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb

and when I run

Get-Mailbox blahblah@itsasecret.edu | fl *exchangeguid*

I get a single result:

ExchangeGuid : cccccccc-cccc-cccc-cccc-cccccccccccc

Basically I have a broken O365 mailbox that has 2 old mailbox guids and 1 new one all for the same user. How can I script running the get-mailbox softdelete, have it store each of the returned old guids (aaa and bbb) as separate variables, store the new guid (ccc) as a variable, and then run:

New-MailboxRestoreRequest -sourcemailbox $VariableA -targetmailbox $VariableC -AllowLegacyDNMismatch

New-MailboxRestoreRequest -sourcemailbox $VariableB -targetmailbox $VariableC -AllowLegacyDNMismatch

I have been doing this by hand copying/pasting the lines in powershell, but I now have to do this on several thousand accounts and one at a time manual isn't cutting it anymore.

Any thoughts are extremely welcome!

I have tried lots of random stuff I've seen online, but none have been able to separate the broken guids into different variables that I can then use.


Solution

  • It doesn't seem you really need to assign the GUIDs to different variables, might be as simple as enumerating each GUID for the soft deleted mailboxes and passing it as argument for New-MailboxRestoreRequest:

    $identity = 'blahblah@itsasecret.edu'
    $targetMbx = (Get-Mailbox -Identity $identity).ExchangeGuid
    (Get-Mailbox -SoftDeletedMailbox -Identity $identity).ExchangeGuid | ForEach-Object {
        $newMailboxRestoreRequestSplat = @{
            SourceMailbox         = $_
            TargetMailbox         = $targetMbx
            AllowLegacyDNMismatch = $true
        }
        New-MailboxRestoreRequest @newMailboxRestoreRequestSplat
    }
    

    Also looking at the description of the -TargetMailbox parameter the first call of Get-Mailbox -Identity $identity might not be needed since the parameter can take the email address as argument:

    The TargetMailbox parameter specifies the GUID of the target mailbox or mail user where you want to restore content to. The target mailbox or mail user needs to exist before you can run this command successfully.

    So, it is possible that the code could be reduced to:

    $identity = 'blahblah@itsasecret.edu'
    (Get-Mailbox -SoftDeletedMailbox -Identity $identity).ExchangeGuid | ForEach-Object {
        $newMailboxRestoreRequestSplat = @{
            SourceMailbox         = $_
            TargetMailbox         = $identity
            AllowLegacyDNMismatch = $true
        }
        New-MailboxRestoreRequest @newMailboxRestoreRequestSplat
    }