Scritps do Office 365 – parte 7: migrando usuários no Exchange Online via script, com o conteúdo do mailbox

 

 

São Paulo (Mais um) Vamos continuar com a nossa série de posts sobre os scripts para administração e deploy do Office365 / BPOS, tanto em PowerShell quanto em VBS. Vale lembrar que esse scritp foi gentilmente disponibilizado pelo grande profissional em Office365, o Cristiano Gonçalves.

Nesse script (em PowerShell), vamos abordar como migrar um usuários on-premises para o Office 365, já criando o endereço de forward. A diferença do post anterior, é que esse script também move o conteúdo do mailbox.

Como parâmetros, deveremos passar as credenciais de conexão e o arquivo texto com a lista de usuários.

Eis o código:

###############################################################################
# PowerShell Source Code
#
# SCRIPT NAME  :  BulkMigrateUsersandMailboxes.ps1
#
# SYNOPSIS     :  Activates a user for Exchange Online and migrates mail content
#          from the on-premise Microsoft Exchange to Microsoft Online
#          Services. Also sets the users MigrationStatus property
###############################################################################

###############################################################################
Set-PsDebug -Strict
###############################################################################

$script:LogFolder   = "MigrationLogs"
$OnPremCred         = Get-Credential "DOMAIN\Administrator"
$MSOLCred           = Get-Credential "admin@impbpos1.microsoftonline.com"
$OnPremiseCas        = "BPOSDEMO1"
$MSOnlineCas        = "red001.mail.microsoftonline.com"

###############################################################################

 

###########################################################################
# Main function and entry to script.
###########################################################################
function Main {

    $LogDir = Get-LogDirectory
   
    # If log file folder doesn’t exist, create it
    if (!(Test-Path $LogDir)){
        New-Item $LogDir -type directory   
    }
   
    $users = Import-Csv -Path "Users.csv"
   
    # Returns active subscriptions only (use DisplayAll to return active and non-active subscriptions)
    $Subscriptions = Get-MSOnlineSubscription  -Credential $MSOLCred
    
    $users | ForEach-Object {
   
        $UserIdentity = $_.Identity
        $UserPassword = $_.Password
        $UserLocation = $_.UserLocation
   
        Start-Transcript -Path "$LogDir\$UserIdentity.txt" -Append
   
        # Enable User in MS Online
        Enable-MSOnlineUser -Credential $MSOLCred -Identity $UserIdentity -Password $UserPassword -SubscriptionIds $Subscriptions.SubscriptionId -UserLocation $UserLocation
   
        # Add Forwarding Address
        Add-XsExchangeForwardingAddress -SourceIdentity $UserIdentity -SourceCredential $OnPremCred -TargetCredential $MSOLCred -Verbose
   
        "Sleeping for 20 seconds"
        # 15 seconds still had failures
        Start-Sleep 20
   
        # Get Local Exchange Mailbox Data
        $LocalMbx = Get-XsHostedExchangeMailbox -SourceIdentity $UserIdentity -SourceServer $OnPremiseCas -SourceAdminCredential $OnPremCred
   
        # Move Mailbox Content
        Move-XsExchangeMailboxToExchangeOnline -SourceIdentity $UserIdentity -SourceCredential $OnPremCred -TargetCredential $MSOLCred  -AllowUnsecureConnection -Verbose
   
        # Get MSOL Mailbox Data
    $OnlineMbx = Get-XsHostedExchangeMailbox -SourceIdentity $UserIdentity -SourceServer $MSOnlineCas -SourceAdminCredential $MSOLCred

    # Compare mailboxes and write result to the Migration Status property of the Microsoft Online User
    $MigrationStatus = Compare-Mailboxes $LocalMbx, $OnlineMbx
        Set-xsMicrosoftOnlineMigrationStatus -Identity  $UserIdentity -MigrationStatus $MigrationStatus -Credential $MSOLcred
       
        Stop-Transcript
    }
}

###########################################################################
# The function to compare the itemcount of mailboxes.
###########################################################################
function Compare-Mailboxes($LocalMbx, $OnlineMbx)
{
    $SourceMailboxItems = 0
    $OnlineMailboxItems = 0

    $LocalMbx.folders  | foreach {$SourceMailboxItems += $_.ItemCount}
    $OnlineMbx.folders | foreach {$OnlineMailboxItems += $_.ItemCount}

    if ($SourceMailboxItems -ne $OnlineMailboxItems)
    {
        "Failed"
    } else {
        "Completed"
    }
}

###########################################################################
# The function sends plain text email to recipient passed in to function.
###########################################################################
function Send-Message($To, $From, $Subject, $Body)
{
    $Msg = new-object System.Net.Mail.MailMessage

    $MsgTo = new-object System.Net.Mail.MailAddress $To

    $Msg.To.Add($MsgTo)
    $Msg.From = $From
    $Msg.Subject = $Subject
    $Msg.Body = $Body   
    $Msg.Bcc.Add($BccTo)
 
    $SmtpClient = new-object system.net.mail.smtpClient
    $SmtpClient.host = $SmtpServer
   
    &{
        trap
        {
            Add-Content $ErrorFile "$([Datetime]::Now) ERROR: $UserLine – $_"
            Write-host -ForegroundColor "red" "Error sending message to $To. Error: $($_.Exception.Message)"
            $Script:TotalNumberOfFailures++
            Continue
        }
        &{
            $SmtpClient.Send($Msg)   
            Add-Content $SuccessFile "$([Datetime]::Now) $UserLine – Mail sent"
        }
    }
}

###########################################################################
# The function returns the log folder required to store transcript files.
###########################################################################
Function Get-LogDirectory
{
    (Split-Path $MyInvocation.ScriptName) + "\$LogFolder"
}

# Start Script
. Main

Abraços,

Carlos Monteiro.

Tags: , , , , , , ,

Deixe uma resposta

Preencha os seus dados abaixo ou clique em um ícone para log in:

Logotipo do WordPress.com

Você está comentando utilizando sua conta WordPress.com. Sair / Alterar )

Imagem do Twitter

Você está comentando utilizando sua conta Twitter. Sair / Alterar )

Foto do Facebook

Você está comentando utilizando sua conta Facebook. Sair / Alterar )

Foto do Google+

Você está comentando utilizando sua conta Google+. Sair / Alterar )

Conectando a %s


%d blogueiros gostam disto: