PowerShell scripts and Microsoft 365

PowerShell scripts can be used to perform various tasks during a migration. This article describes the default scripts that are run when migrating to Microsoft 365 (and are the default scripts in the migration tool).

Both of these scripts make use of PowerShell replacement variables

Init Script

The init script initializes a remote PowerShell session with the Microsoft 365 servers. If you are migrating to Office 365 you should not have to change this script.

# Set this so that errors are thrown from Cmdlets
$ErrorActionPreference = 'Stop'
# Open the connection
$sesh = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri [!ps-url] -credential (New-Object -TypeName System.Management.Automation.PSCredential -argumentlist '[!admin-email]',(ConvertTo-SecureString '[!admin-password]' -AsPlainText -Force)) -Authentication Basic -AllowRedirection
# Import the session
$imp = Import-PSSession -Session $sesh

Before Script

The before script checks that the specified user exists in Microsoft 365, and creates it if not.

 # Set this so that errors are thrown from Cmdlets
$ErrorActionPreference = 'Stop'
# Check if a user exists
Function UserExists() {
    trap {
        return $false
    Get-User -Identity [!user-importname]@[!admin-domain]
    return $true
# Create a user if it doesn't exist
Function CreateUser() {
    $ret = UserExists
    if ($ret -eq $false) {
        New-Mailbox -Name '[!user-givenname] [!user-familyname]' -MicrosoftOnlineServicesID [!user-importname]@[!admin-domain] -Password (ConvertTo-SecureString -String '[!user-password]' -AsPlainText -Force)
        # Allow some time for the account to become active
        Start-Sleep –s 15

Deployment Modules

The default scripts provided with the tool may need to be altered if you require different functionality, or if you would like to use the Microsoft365 Deployment Modules

Error Messages

The tool determines whether a script has run successfully if no exception is thrown from the script. In PowerShell, internal cmdlets handle their own errors unless instructed to do so in the script. It is usually important to include the global statement $ErrorActionPreference = 'Stop', in the script.

You can also throw your own custom exception from scripts if required which will then be displayed in the user interface and trace files.

Was this article helpful?
0 out of 0 found this helpful