Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <# Script to enable a new remote mailbox
- An AD user object that has been synchronized to O365 needs to already be created
- So the user must already be created in AD and synced to 365 before we can run this script to create the mailbox and assign license.
- Update 12/11/2017
- - Removed hard set server names, added logic to dynamically find Exchange on-premises PowerShell endpoint
- - Removed option to assign licenses other than E3
- - Added logic to accomodate UPN's other than @quantaservices.com
- - Cleaned up recipient validation logic and added check for UPN to email address collision
- - Added logic to dynamically create RemoteRoutingAddress
- Update 2/4/201
- - Added a check for mail enabled user
- Updated 10/7/2014
- - Fixed requireS statement in script
- - Added CleanExit function
- Updated 9/22/2014
- - Fixed error trap on Set-MSOLUser and Set-MsolUserLicenses cmdlets
- Updated 8/6/2014
- - Fixed error trap on Enable-RemoteMailbox cmdlet
- Updated 7/7/2014
- - Do not assign license to Room or Equipment mailboxes
- Updated 7/1/2014
- - Changed check for proxyAddresses to only look for SMTP:, fixing an issue when user was enabled for Lync before creating a mailbox.
- Updated 4/22/2014
- - Changed check of proxyAddresses to existence only
- - Added checks for attributes: mDBUseDefaults,msExchHomeServerName,msExchUMDtmfMap,msExchUserAccountControl
- - Replaced Pause command with ReadKey function
- - Commented out initial Company field warning
- - Added CredDelete method to ADVAPI32
- - Added check for class to ADVAPI32get-adus
- Updated 3/19/2014
- - Added URL to country code list
- Updated 3/6/2014
- - Slightly modified how licenses are displayed
- Updated 3/3/2014
- - License assignment choice by user (from Microsoft Office 365 Plan E4 or Exchange Online Plan 1)
- - Added check for Company attribute
- - Pulls country code from C user attribute
- - Added Pause if run from ConsoleHost
- Updated 1/1/2014
- - Digitally signed
- - Logs into Exchange on prem and Office 365 using same credentials pulled from Credential Manager
- Created 10/2013
- ToDo:
- - Check that user has rights to assign license in 365 before creating mailbox
- -
- #>
- #requires -version 3
- #requires -module ActiveDirectory
- param()
- Import-Module ActiveDirectory -ErrorAction Stop
- Import-Module MSOnline -ErrorAction Stop
- $script:session = $null
- $script:userLogonName = $null
- $script:countryCode = $null
- $script:adminCreds = $null
- # Prompt for exit, if run from windowed PowerShell
- function CleanExit() {
- If ($Host.Name -eq "ConsoleHost") { Write-Host "Press any key to continue..."; $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") | Out-Null }
- Exit
- }
- # The following credential manager stuff was taken from the MS script O365-Fed-MetaData-Update-Task-Installation used on the ADFS servers
- function GetCredentialsFromCredentialManager() {
- Write-Host "Retrieving admin credentials from credential manager" -ForegroundColor Green
- $sig = @"
- [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
- public struct NativeCredential
- {
- public UInt32 Flags;
- public CRED_TYPE Type;
- public IntPtr TargetName;
- public IntPtr Comment;
- public System.Runtime.InteropServices.ComTypes.FILETIME LastWritten;
- public UInt32 CredentialBlobSize;
- public IntPtr CredentialBlob;
- public UInt32 Persist;
- public UInt32 AttributeCount;
- public IntPtr Attributes;
- public IntPtr TargetAlias;
- public IntPtr UserName;
- internal static NativeCredential GetNativeCredential(Credential cred)
- {
- NativeCredential ncred = new NativeCredential();
- ncred.AttributeCount = 0;
- ncred.Attributes = IntPtr.Zero;
- ncred.Comment = IntPtr.Zero;
- ncred.TargetAlias = IntPtr.Zero;
- ncred.Type = CRED_TYPE.GENERIC;
- ncred.Persist = (UInt32)1;
- ncred.CredentialBlobSize = (UInt32)cred.CredentialBlobSize;
- ncred.TargetName = Marshal.StringToCoTaskMemUni(cred.TargetName);
- ncred.CredentialBlob = Marshal.StringToCoTaskMemUni(cred.CredentialBlob);
- ncred.UserName = Marshal.StringToCoTaskMemUni(System.Environment.UserName);
- return ncred;
- }
- }
- [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
- public struct Credential
- {
- public UInt32 Flags;
- public CRED_TYPE Type;
- public string TargetName;
- public string Comment;
- public System.Runtime.InteropServices.ComTypes.FILETIME LastWritten;
- public UInt32 CredentialBlobSize;
- public string CredentialBlob;
- public UInt32 Persist;
- public UInt32 AttributeCount;
- public IntPtr Attributes;
- public string TargetAlias;
- public string UserName;
- }
- public enum CRED_TYPE : uint
- {
- GENERIC = 1,
- DOMAIN_PASSWORD = 2,
- DOMAIN_CERTIFICATE = 3,
- DOMAIN_VISIBLE_PASSWORD = 4,
- GENERIC_CERTIFICATE = 5,
- DOMAIN_EXTENDED = 6,
- MAXIMUM = 7, // Maximum supported cred type
- MAXIMUM_EX = (MAXIMUM + 1000), // Allow new applications to run on old OSes
- }
- public class CriticalCredentialHandle : Microsoft.Win32.SafeHandles.CriticalHandleZeroOrMinusOneIsInvalid
- {
- public CriticalCredentialHandle(IntPtr preexistingHandle)
- {
- SetHandle(preexistingHandle);
- }
- public Credential GetCredential()
- {
- if (!IsInvalid)
- {
- NativeCredential ncred = (NativeCredential)Marshal.PtrToStructure(handle,
- typeof(NativeCredential));
- Credential cred = new Credential();
- cred.CredentialBlobSize = ncred.CredentialBlobSize;
- cred.CredentialBlob = Marshal.PtrToStringUni(ncred.CredentialBlob,
- (int)ncred.CredentialBlobSize / 2);
- cred.UserName = Marshal.PtrToStringUni(ncred.UserName);
- cred.TargetName = Marshal.PtrToStringUni(ncred.TargetName`);
- cred.TargetAlias = Marshal.PtrToStringUni(ncred.TargetAlias);
- cred.Type = ncred.Type;
- cred.Flags = ncred.Flags;
- cred.Persist = ncred.Persist;
- return cred;
- }
- else
- {
- throw new InvalidOperationException("Invalid CriticalHandle!");
- }
- }
- override protected bool ReleaseHandle()
- {
- if (!IsInvalid)
- {
- CredFree(handle);
- SetHandleAsInvalid();
- return true;
- }
- return false;
- }
- }
- [DllImport("Advapi32.dll", EntryPoint = "CredReadW", CharSet = CharSet.Unicode, SetLastError = true)]
- public static extern bool CredRead(string target, CRED_TYPE type, int reservedFlag, out IntPtr CredentialPtr);
- [DllImport("Advapi32.dll", EntryPoint = "CredFree", SetLastError = true)]
- public static extern bool CredFree([In] IntPtr cred);
- [DllImport("Advapi32.dll", SetLastError=true, EntryPoint="CredWriteW", CharSet=CharSet.Unicode)]
- public static extern bool CredWrite([In] ref Credential userCredential, [In] UInt32 flags);
- [DllImport("Advapi32.dll", EntryPoint = "CredDelete", CharSet = CharSet.Unicode, SetLastError = true)]
- public static extern bool CredDelete(string target, CRED_TYPE type, int reservedFlag);
- "@
- If (-not ([System.Management.Automation.PSTypeName]'ADVAPI32.Util').Type) {
- Add-Type -MemberDefinition $sig -Namespace "ADVAPI32" -Name 'Util'
- }
- $readtargetName = "Microsoft-Office365-NewMailboxCred"
- $nCredPtr= New-Object IntPtr
- $success = [ADVAPI32.Util]::CredRead($readtargetName,1,0,[ref] $nCredPtr)
- if($success){
- $critCred = New-Object ADVAPI32.Util+CriticalCredentialHandle $nCredPtr
- $readCred = $critCred.GetCredential()
- $UserName = $readCred.UserName
- $Password = $readCred.CredentialBlob
- $Password = ConvertTo-SecureString -String $Password -AsPlainText -Force
- $script:adminCreds = New-Object Management.Automation.PSCredential $UserName, $Password
- Write-Host "`n`tSuccessfully retrieved credentials from credential manager" -ForegroundColor Yellow
- } else {
- Write-Host "`n`tCredentials not found" -ForegroundColor Red
- }
- }
- # The following credential manager stuff was taken from the O365-Fed-MetaData-Update-Task-Installation used on the ADFS servers
- function SaveCredentialsInCredentialManager() {
- $saveCred = New-Object ADVAPI32.Util+Credential
- $saveCred.flags = 0
- $saveCred.type = 1
- #Get MSOL creds
- While (!$UserName) { $UserName = (Read-Host "`n Admin username (user`@domain)").ToUpper(); }
- #Set the name of the CredMan credentials
- $saveCred.targetName = "Microsoft-Office365-NewMailboxCred"
- $saveCred.userName = $UserName
- $saveCred.attributeCount = 0
- $saveCred.persist = 2
- While (!$Password) { $Password = Read-Host -assecurestring "`n Admin password"; }
- $objCreds = New-Object Management.Automation.PSCredential $UserName, $Password
- $Password = $objCreds.GetNetworkCredential().Password
- #Validating MSOL creds
- Write-Host "Validating credentials with O365..." -ForegroundColor Green
- Connect-MsolService -Credential $objCreds
- if ($?) {
- Write-Host "`n`tSuccess" -ForegroundColor Green
- } else {
- Write-Host "`n`tFailed credential validation. Exiting...`n" -ForegroundColor Red
- CleanExit
- }
- $saveCred.credentialBlobSize = [System.Text.Encoding]::Unicode.GetBytes($Password).length
- $saveCred.credentialBlob = $Password
- #Store the MSOL creds in CredMan
- $CredWrite = [ADVAPI32.Util]::CredWrite([ref]$saveCred,0)
- If ($CredWrite)
- {
- Write-Host "`n`tAdded credentials to the local Credential Manager" -ForegroundColor Green
- }
- Else
- {
- Write-Host "`n`tFailed adding credentials to the local Credential Manager. Exiting...`n" -ForegroundColor Red
- CleanExit
- }
- }
- # Create a tenant PSSession.
- function CreateTenantSession() {
- #Find Exchange 2013 Client Access Servers
- [array]$arrServers = Get-ADObject -LDAPFilter "(&(objectCategory=msexchExchangeServer)(msExchCurrentServerRoles:1.2.840.113556.1.4.803:=16385))" -SearchBase ([ADSI]"LDAP://RootDSE").configurationNamingContext.ToString() | foreach {
- $domainName = $_.DistinguishedName -split "," -match "^DC=" -replace "^DC=" -join "."
- "$($_.Name).$domainName".ToUpper()
- }
- # connect to exchange online tenant
- # we must skip the certificate check because we are connecting to a specifc server, not the friendly webmail dns name
- $psOptions = New-PSSessionOption -SkipCACheck -SkipCNCheck -SkipRevocationCheck -OpenTimeout 2000
- while ($script:session -eq $null -and $arrServers.Count -gt 0) {
- $objServer, $arrServers = $arrServers | sort {Get-Random}
- Write-Host "`r`nAttempting to connect to $objServer..." -NoNewline
- try {
- $script:session = New-PSSession -SessionOption $psOptions -ConfigurationName Microsoft.Exchange -ConnectionUri http://$objServer/Powershell -Credential $script:adminCreds -ErrorAction Stop
- Write-Host "success`r`n"
- }
- catch {
- Write-Host "unsuccessful`r`n"
- if ($_.Exception -match 'bad password') {
- Write-Host "Input credentials are incorrect"`r`n -ForegroundColor Red
- CleanExit
- }
- }
- }
- if ($script:session -eq $null)
- {
- Write-Host "Could not establish connection to Exchange"`r`n -ForegroundColor Red
- CleanExit
- }
- else
- {
- $params = @{
- "Session" = $script:session
- "AllowClobber" = $true
- "DisableNameChecking" = $true
- "CommandName" = "Enable-RemoteMailbox","Get-Recipient"#,"Get-Mailbox","Get-RemoteMailbox","Update-AddressList","Update-GlobalAddressList"
- }
- if ( -not (&"Import-PSSession" @params))
- {
- Write-Host "Exchange session cannot be imported to current PowerShell window."`r`n -ForegroundColor Red
- Remove-PSSession $script:session
- CleanExit;
- }
- }
- }
- function DisconnectTenantSession($errorMsg) {
- if($errorMsg) {
- Write-Host $errorMsg`r`n -ForegroundColor Red -BackgroundColor Black
- }
- if($script:session) {
- Write-Host "Disconnecting from Exchange..."`r`n
- Remove-PSSession $script:session
- }
- }
- function CreateMailbox() {
- if($script:userLogonName) {
- # Check that the user object exists
- try {
- $ADUser = Get-ADUser $script:userLogonName -Properties msExchRecipientDisplayType,proxyaddresses,c,company,mDBUseDefaults,msExchHomeServerName,msExchUMDtmfMap,msExchUserAccountControl,ObjectGUID -ErrorAction SilentlyContinue
- } catch {
- DisconnectTenantSession("User does not exist in AD.")
- CleanExit
- }
- # Use country from AD user object, if it exists
- $script:countryCode = $ADUser.c
- If (-not $script:countryCode) {
- Write-Host "`r`nVisit http://www.dovestones.com/country-codes-used-active-directory/ for a list of valid country codes." -ForegroundColor Yellow
- $script:countryCode = Read-Host " New user country code (press <Enter> for US)"
- if ([string]::IsNullOrEmpty($script:countryCode)) {
- $script:countryCode = "US"
- Write-Host "`r`nUsing default country code of US" -ForegroundColor Yellow
- }
- }
- Else { Write-Host "`n`tSuccessfully retrieved countryCode from AD: $script:countryCode`r`n" -ForegroundColor Yellow; }
- # Get list of valid UPN suffixes
- $UpnSuffixes = Get-ADForest | select -ExpandProperty UPNSuffixes | sort
- $strUpnSuffixes = $UpnSuffixes -join "){1}$|^.+(@"
- # Check that the UPN is valid
- $isValidUPN = $ADUser.UserPrincipalName -match "^.+(@$strUpnSuffixes){1}$"
- if(-not($isValidUPN)) {
- $localPrefix = $ADUser.UserPrincipalName -replace "@.*$"
- DisconnectTenantSession("`r`nError: username is currently setup as $($ADUser.UserPrincipalName).`r`n")
- Write-Host "`n`tTo correct this, please follow the instructions below.`r`n" -ForegroundColor Yellow
- Write-Host "`n`tUsername must be in the following format: $($localPrefix)@<domain name>, where <domain name> matches one of the following:`r`n`t`t$($UpnSuffixes -join "`r`n`t`t")`r`n`tIn the ADUC Account tab, change the user logon suffix to a valid domain name from the drop down next to the User Logon Name." -ForegroundColor Green
- CleanExit
- }
- # Check that the Company field exists
- $isValidCompany = ![string]::IsNullOrEmpty($ADUser.Company)
- if(-not $isValidCompany) {
- DisconnectTenantSession("`r`nError: username $($ADUser.UserPrincipalName) does not have the Company attribute set.`r`n")
- Write-Host "`n`tTo correct this, please follow the instructions below.`r`n" -ForegroundColor Yellow
- Write-Host "`n`tIn the ADUC Organization tab, enter the company name in the Company field." -ForegroundColor Green
- CleanExit
- }
- # Check that the user has been created in O365 (i.e. Dirsync has run once)
- Connect-MsolService -Credential $script:adminCreds -ErrorAction Stop
- $msolUser = Get-MsolUser -UserPrincipalName $ADUser.UserPrincipalName -ErrorAction SilentlyContinue
- if(-not($msolUser)) {
- DisconnectTenantSession("`r`nUser not found in Office 365.")
- Write-Host "`n`tSynchronization runs every 30 minutes." -ForegroundColor Yellow
- Write-Host "`n`tIf you still receive this message after 45 minutes, please contact QCO IT - Messaging (QCOIT-Messaging@QuantaServices.com).`r`n" -ForegroundColor Yellow
- CleanExit
- }
- # Connect to Exchange
- CreateTenantSession
- #Check for conflicting recipients
- $conflictingRecipient = Get-Recipient -Filter "(EmailAddresses -eq '$($ADUser.UserPrincipalName)') -and (Guid -ne '$($ADUser.ObjectGuid)')"
- if (-not($conflictingRecipient -eq $null)) {
- $strMailboxLocation = `
- if ($conflictingRecipient.Count -gt 1) {
- "Multiple recipients"
- }
- elseif ($conflictingRecipient.RecipientTypeDetails -match "^Remote") {
- "Office 365 recipient"
- }
- else {
- "Quanta hosted recipient"
- }
- DisconnectTenantSession("$strMailboxLocation already exists with this email address: $($ADUser.UserPrincipalName). Please verify the logon name.`r`n")
- CleanExit
- }
- # Check that the mDBUseDefaults attribute isn't set
- # This is an indication that the account was copied from AD and retains some Exchange related properties that cause the Enable-RemoteMailbox command to fail
- if([string]::IsNullOrEmpty($ADUser.mDBUseDefaults) -eq $false) {
- DisconnectTenantSession("`r`nError: username $($ADUser.UserPrincipalName) has the 'mDBUseDefaults' attribute set.`r`n")
- Write-Host "`n`tTo correct this, please follow the instructions below.`r`n" -ForegroundColor Yellow
- Write-Host "`n`tIn the ADUC Attribute Editor tab, remove the 'mDBUseDefaults' attribute value." -ForegroundColor Green
- CleanExit
- }
- # Check that the msExchHomeServerName attribute isn't set
- # This is an indication that the account was copied from AD and retains some Exchange related properties that cause the Enable-RemoteMailbox command to fail
- if($ADUser.msExchHomeServerName -ne $null -and $ADUser.msExchHomeServerName -ne "") {
- DisconnectTenantSession("`r`nError: username $($ADUser.UserPrincipalName) has the 'msExchHomeServerName' attribute set.`r`n")
- Write-Host "`n`tTo correct this, please follow the instructions below.`r`n" -ForegroundColor Yellow
- Write-Host "`n`tIn the ADUC Attribute Editor tab, remove the 'msExchHomeServerName' attribute value." -ForegroundColor Green
- CleanExit
- }
- # Only run these checks if NOT a mail enabled user
- If ($ADUser.msExchRecipientDisplayType -ne 6) {
- # Check that the msExchUMDtmfMap attribute isn't set
- # This is an indication that the account was copied from AD and retains some Exchange related properties that cause the Enable-RemoteMailbox command to fail
- if([string]::IsNullOrEmpty($ADUser.msExchUMDtmfMap) -eq $false) {
- DisconnectTenantSession("`r`nError: username $($ADUser.UserPrincipalName) has the 'msExchUMDtmfMap' attribute set.`r`n")
- Write-Host "`n`tTo correct this, please follow the instructions below.`r`n" -ForegroundColor Yellow
- Write-Host "`n`tIn the ADUC Attribute Editor tab, remove the 'msExchUMDtmfMap' attribute value." -ForegroundColor Green
- CleanExit
- }
- # Check that the msExchUserAccountControl attribute isn't set
- # This is an indication that the account was copied from AD and retains some Exchange related properties that cause the Enable-RemoteMailbox command to fail
- if([string]::IsNullOrEmpty($ADUser.msExchUserAccountControl) -eq $false) {
- DisconnectTenantSession("`r`nError: username $($ADUser.UserPrincipalName) has the 'msExchUserAccountControl' attribute set.`r`n")
- Write-Host "`n`tTo correct this, please follow the instructions below.`r`n" -ForegroundColor Yellow
- Write-Host "`n`tIn the ADUC Attribute Editor tab, remove the 'msExchUserAccountControl' attribute value." -ForegroundColor Green
- CleanExit
- }
- # Check that the proxyAddresses attribute isn't set
- # This is an indication that the account was copied from AD and retains some Exchange related properties that cause the Enable-RemoteMailbox command to fail
- if($ADUser.proxyAddresses -match "^smtp:") {
- DisconnectTenantSession("`r`nError: username $($ADUser.UserPrincipalName) has proxy addresses.`r`n")
- Write-Host "`n`tTo correct this, please follow the instructions below.`r`n" -ForegroundColor Yellow
- Write-Host "`n`tIn the ADUC Attribute Editor tab, remove the 'proxyAddresses' attribute value(s)." -ForegroundColor Green
- CleanExit
- }
- }
- # Create the remote mailbox
- Write-Host "Enabling remote mailbox..." -ForegroundColor Green
- try {
- Write-Host "Choose which type of mailbox to create:"
- Write-Host " 1 - User Mailbox (or, just press <Enter>)"
- Write-Host " 2 - Room Mailbox"
- Write-Host " 3 - Equipment Mailbox"
- Write-Host " 4 - Shared Mailbox"
- Write-Host " 5 - Service Account Mailbox"
- $mailboxType = Read-Host "Selection"
- if ([string]::IsNullOrEmpty($mailboxType)) {
- $mailboxType = 1
- Write-Host "`n`tUsing default mailbox type of 'User Mailbox'"
- }
- # Find unique remote routing address
- $EmailAddressPrefix = $ADUser.UserPrincipalName -split "@" | select -First 1
- $RemoteRoutingAddress = "$EmailAddressPrefix@quantaservices.mail.onmicrosoft.com"
- $AddressInUse = Get-Recipient $RemoteRoutingAddress -ErrorAction SilentlyContinue
- while (($AddressInUse -ne $null) -and ($AddressInUse.Guid -ne $ADUser.ObjectGuid)) {
- $RemoteRoutingAddress = `
- if ($EmailAddressPrefix -match "(?<EndingNumber>\d+)$") {
- $IncreaseDigit = ([int]$Matches['EndingNumber']) + 1
- $EmailAddressPrefix = $EmailAddressPrefix -replace "$($Matches['EndingNumber'])$",$IncreaseDigit
- "$EmailAddressPrefix@quantaservices.mail.onmicrosoft.com"
- } else {
- "$EmailAddressPrefix`1@quantaservices.mail.onmicrosoft.com"
- }
- $AddressInUse = Get-Recipient $RemoteRoutingAddress -ErrorAction SilentlyContinue
- }
- # Create hashtable to hold parameters passed to Enable-RemoteMailbox cmdlet
- $hashEnableRemoteMailboxParams = @{
- Identity = $ADUser.ObjectGuid.ToString();
- RemoteRoutingAddress = $RemoteRoutingAddress;
- ErrorAction = "Stop";
- }
- $EOP2Only = $false
- switch ($mailboxType) {
- 1 { #User mailbox
- break
- }
- 2 { #Room mailbox
- $hashEnableRemoteMailboxParams["Room"] = $true
- $EOP2Only = $true
- break
- }
- 3 { #Equipment mailbox
- $hashEnableRemoteMailboxParams["Equipment"] = $true
- $EOP2Only = $true
- break
- }
- 4 { #Shared mailbox
- $EOP2Only = $true
- Write-Host "To complete the setup of the Shared Mailbox, please refer to the `“How to setup a Shared Mailbox`” process document." -ForegroundColor Yellow -BackgroundColor Black
- break
- }
- 5 { #Service account mailbox
- $EOP2Only = $true
- break
- }
- default { #Unknown
- DisconnectTenantSession("Invalid selection")
- CleanExit
- }
- }
- Enable-RemoteMailbox @hashEnableRemoteMailboxParams | Out-Null
- } catch {
- DisconnectTenantSession("Error enabling remote mailbox")
- CleanExit
- }
- # Assign the license to the user
- Write-Host "Licensing user..." -ForegroundColor Green
- try {
- # region prep for license assignment
- if ($msolUser.UsageLocation -ne $script:countryCode) {
- Write-Host "`n`tSetting user location to $script:countryCode" -ForegroundColor Yellow
- Set-MSOLUser -UserPrincipalName $msolUser.UserPrincipalName -UsageLocation $script:countryCode -ErrorAction Stop
- }
- # assign licenses
- $LicenseAccountSku =`
- if ($EOP2Only) {
- # Assign EOP2 only
- "quantaservices:EXCHANGEENTERPRISE"
- } else {
- # Assign full E3
- "quantaservices:ENTERPRISEPACK"
- }
- [bool]$LicenseNeeded = -not ($msolUser.Licenses.AccountSkuId -contains $LicenseAccountSku)
- if ($LicenseNeeded) {
- Write-Host "`n`tAssigning license" -ForegroundColor Yellow
- Set-MsolUserLicense -UserPrincipalName $msolUser.UserPrincipalName -AddLicenses $LicenseAccountSku -ErrorAction Stop
- } else {
- Write-Host "`n`tUser already has license assigned" -ForegroundColor Yellow
- }
- } catch {
- DisconnectTenantSession("Error assigning license")
- }
- # Disconnect from Exchange
- DisconnectTenantSession
- } else {
- Write-Host "Invalid input" -ForegroundColor Red -BackgroundColor Black
- }
- }
- Write-Host `r`n
- Write-Host "This script will create a new Office 365 mailbox for an existing AD user." -ForegroundColor Green
- Write-Host "The mailbox should be created within 2 hours of successfully running this script.`r`n" -ForegroundColor Green
- #Write-Host "The 'Company' field of the user account must have a value!`r`n" -ForegroundColor Yellow
- # Retrieve the credentials
- GetCredentialsFromCredentialManager
- if(-not($script:adminCreds)) {
- SaveCredentialsInCredentialManager
- GetCredentialsFromCredentialManager
- if(-not($script:adminCreds)) {
- DisconnectTenantSession("There was an issue retrieving your credentials from the connection manager.")
- CleanExit
- }
- }
- $script:userLogonName = Read-Host "`n`n New user logon name (pre-Windows 2000)"
- CreateMailbox
- CleanExit
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement