5680

A common issue amongst MSPs is the inability to mailshot all of your users in one go. As we know, these are forever changing, and would require constant updates.

Furthermore, some PSAs allow the syncing of tenants to their CRM to be able to log tickets against your users. But we do not want all of the service accounts and unlicensed users, right?

Well, here is a script to help you achieve such greatness.

DISCLAIMER! Running this code, you do so at YOUR OWN RISK. I have included a line that you can include to aim this at 1 tenant, or a tenant at a time, if you wish to do so.

This script will:

1. Cycle through each of your delegate tenants and
2. Create a mail enabled security group with a name of your choice and
3. Exclude certain words like info, sales (you can amend these) and
3. Update that list on further runs.

I would recommend using the line to specify just one of your clients first, so you can see the results.

Who Are We?

Growth MSP is an MSP for MSPs. We are manage migration projects from start to finish, at a price that means we can all make money. We aim to take the stress away, whilst allowing you to not put off sales due to lack of capacity.

The Code

Note here you will need to generate a secure app in your Office 365 tenant that has delegate access. Credit to Cyberdrain – Kelvin Tegelaar – https://www.cyberdrain.com/connect-to-exchange-online-automated-when-mfa-is-enabled-using-the-secureapp-model/

Set-ExecutionPolicy RemoteSigned

## Declare variables
## You need to create an application in your tenant and populate them below
## Credit to Cyberdrain - Kelvin Tegelaar - https://www.cyberdrain.com/connect-to-exchange-online-automated-when-mfa-is-enabled-using-the-secureapp-model/
## You use this script at YOUR OWN RISK. I suggest you test on 1 domain first, see below
	
 $ApplicationId = ''
 $ApplicationSecret = '' | Convertto-SecureString -AsPlainText -Force
 $TenantID = ''
 $RefreshToken = ''
 $ExchangeRefreshToken = ''
 $upn = '' ## Enter your delegate username here 
 $GroupName = "" ## Enter the group name you want to create here 

$credential = New-Object System.Management.Automation.PSCredential($ApplicationId, $ApplicationSecret)

$aadGraphToken = New-PartnerAccessToken -ApplicationId $ApplicationId -Credential $credential -RefreshToken $refreshToken -Scopes 'https://graph.windows.net/.default' -ServicePrincipal -Tenant $tenantID

$graphToken = New-PartnerAccessToken -ApplicationId $ApplicationId -Credential $credential -RefreshToken $refreshToken -Scopes 'https://graph.microsoft.com/.default' -ServicePrincipal -Tenant $tenantID

Connect-MsolService -AdGraphAccessToken $aadGraphToken.AccessToken -MsGraphAccessToken $graphToken.AccessToken

Connect-AzureAD -AadAccessToken $aadGraphToken.AccessToken -AccountId $upn -MsAccessToken $graphToken.AccessToken -TenantId $tenantID

$customers = Get-MsolPartnerContract -All

## If you want to test it on one customer first use this, and enter their default Office 365 domain name 
## $customers = Get-MsolPartnerContract | Where-Object{$_.DefaultDomainName -match "yourcustomer.onmicrosoft.com"}

foreach($customer in $customers){

$token = New-PartnerAccessToken -ApplicationId 'a0c73c16-a7e3-4564-9a95-2bdf47383716' -RefreshToken $ExchangeRefreshToken -Scopes 'https://outlook.office365.com/.default' -Tenant $customer.TenantId

$tokenValue = ConvertTo-SecureString "Bearer $($token.AccessToken)" -AsPlainText -Force

$credential = New-Object System.Management.Automation.PSCredential($upn, $tokenValue)

$customerId = $customer.DefaultDomainName
$session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri "https://ps.outlook.com/powershell-liveid?DelegatedOrg=$($customerId)&BasicAuthToOAuthConversion=true" -Credential $credential -Authentication Basic -AllowRedirection

Write-host "Connected to " + $customerId -ForegroundColor Green -NoNewline    

Import-PSSession $session

$GroupExists = Get-AzureADGroup -Filter "DisplayName eq '$GroupName'"
		
 if ($GroupExists -ne $NULL)
  {
   Write-Host "Group has already been created."
  }
   else
  {
   $EmailAddress = $GroupName + "@" + $customerid 	
   New-DistributionGroup -Name $GroupName -Alias $GroupName -Type "Security" -PrimarySmtpAddress $EmailAddress -RequireSenderAuthenticationEnabled $false
			}
## Use this line instead if you want to exclude license types ## Use this line instead if you want to exclude license types for example AAD_PREMIUM_P2 - this will exclude that user totally if they have that license.

## $UserLic = Get-MsolUser -All -TenantID $customer.TenantId | Where ({$_.isLicensed -eq "TRUE" -and  $_.licenses.AccountSkuId -notcontains "somelicense"})
	
$UserLic = Get-MsolUser -All -TenantID $customer.TenantId | Where ({$_.isLicensed -eq "TRUE"})
 

 $SecurityName = @$GroupName 
 $LikeArray = @("sale*","accounts*","hello*","enquiries*","website*","admin*","support*","guest*","office*","lab*","scanner*","book*","engineer*","operations*","travel*","help*","info*","print*")

foreach ($user in $UserLic)     
 { 
  $AddToDL = $true
   if ($SecurityName -notcontains $user)      
    { 
    foreach ($email in $LikeArray)
     {
      if ($user.UserPrincipalName -like $email)
       {
	$AddToDL = $false
       }
     }
   if ($AddToDL -eq $true)   	
    {
     write-host $user.UserPrincipalName " has been added."
     Add-DistributionGroupMember -Identity $GroupName -Member $user.UserPrincipalName -BypassSecurityGroupManagerCheck -ErrorAction stop
    }
  }
   else 
 {         
   write-host $user.UserPrincipalName " this user matches a blocked address and will not be added"         
 }
}
}
Get-PSSession | Remove-PSSession

What Happens When You Run This Code?

Running this script create a mail enabled security group on each of your delegate tenants.

Want More Expert Tips Like This?

We’ve got dozens of tips and tricks like this to make your life as an MSP a little easier. We also offer expert mentorship, advice, and support for every aspect of an MSP’s business, including sales, marketing, support, and engineering. If you need help growing your MSP, please contact us today.

Share

Post comment

Your email address will not be published. Required fields are marked *

Go top