Public/Conver-MailboxToShared.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
##################################################################################################
# Convert-MailboxToShared
# Converts mailboxes to shared and removes licenses if prompted in Office 365
##################################################################################################
Function Convert-MailboxToShared(){
    #Install/Import Modules
    Check-Module -ModuleToFind "MSOnline"

    #Connect to Exchange
    $result = Connect-ExchangeSession

    #Connect to MsolService to remove licenses
    Connect-MsolService -Credential $result.Credential

    #Capture Mailbox for share conversion
    $mb = read-host "Enter all mailbox alias seperated by commas (i.e. user1,user2,user3)"

    #Split the array of items that are seperated by commas.
    $mbarray = $mb -Split ','

    #Check if more than one account for better grammer in the read-host $removeLicensesCheck prompt
    $plural = "this"
    if($mbarray.Length -gt 1){
        $plural = "all of these"
    }
    
    #Check if tech wishes to remove Office 365 licenses from the accounts associated with the list of aliases
    $removeLicensesCheck = Read-Host "Do you want to remove Office 365 Licenses for $plural accounts?(y or n)"
    
    #Running the command that is between the brackets on each item ($i) in the array using each item as the variable.
    $removed = $false
    Foreach ($i in $mbarray){
        #convert mailbox to shared mailbox
        Set-Mailbox $i -Type shared
    
        #Variablize the mailbox associated with the alias
        $m = get-mailbox $i
        
        #remove office 365 licenses if desire was indicated to do so.
        if($RemoveLicensesCheck -eq "y"){
            #Remove all office 365 licenses for each account in mbarray
            (get-MsolUser -UserPrincipalName $m.UserPrincipalName).licenses.AccountSkuId |foreach{ Set-MsolUserLicense -UserPrincipalName $m.UserPrincipalName -RemoveLicenses $_ }
            $removed = $true
        }
    }
    
    #Removing the PSSession
    Remove-PSSession $result.Session
    
    #Final test output to indicate all commands processed.
    If($removed -eq $true){
        Read-Host -prompt "All requested mailboxes converted to shared and licenses have been removed unless errors are displayed. You may now exit this script."
    } else {
        Read-Host -prompt "All requested mailboxes converted to shared unless errors are displayed. You may now exit this script."
    }
}