Search code examples
powershelloffice365exchange-server

Is there any logic like if else or any other command in powershell to get the powershell script non-interactive?


I am preparing the powershell script to move the local mailbox to online mailbox via powershell script and after migration will assign the license

Below is the sample:

#Created the user in AD , not mentioned here 
Enable-Mailbox -Identity "$firstname $lastname" -Database "XXXXXXX"
Start-Sleep -Seconds 10
Set-Mailbox "$firstname.$lastname" -PrimarySmtpAddress "$firstname.$lastname@XXXXXXX" -EmailAddressPolicyEnabled $false

Is there any logic like if-else or something else which i can use here which trigger the below command once the user mailbox is sync from local exchange to online exchange ?So below command is run successfully without any issue or error.

Connect-ExchangeOnline
$Mailbox = "$firstname.$lastname@XXXXXXX"
$Endpoint = "XXXXXXXX"
$TargetDomain = "XXXXXXXXXXX"
$Cred = Get-Credential
New-MoveRequest -Identity $Mailbox -Remote -RemoteHostName $Endpoint -TargetDeliveryDomain $TargetDomain -RemoteCredential $Cred -Batchname "$Mailbox Move to O365"

Is there any logic like if-else or something else which i can use here which trigger the below command once the mailbox migration is done then below command is execute?

#Assign the license once migration is done successfully 
Set-MsolUser -UserPrincipalName $Mailbox -UsageLocation US
Set-MsolUserLicense -UserPrincipalName $Mailbox -AddLicenses "XXXXXXXXXXXX"

Note-I can use the Start-Sleep -Seconds XXX in between but sync time is not same everytime


Solution

  • in order to assign a license after the migration of the mailboxes ; you need first to check the status of the move-request within a while loop and execute your commands if the status changed to Completed as follow:

    $i = $true
    while ($i){
    
        if (Get-MoveRequest -Identity $Mailbox| where {$_.status -eq "Completed"}) {
    
            Set-MsolUser -UserPrincipalName $Mailbox -UsageLocation US
            Set-MsolUserLicense -UserPrincipalName $Mailbox -AddLicenses "XXXXXXXXXXXX"
            $i = $False
        } else {
                sleep 10
               }
    
    }