PowerShell: A Microsoft 365 Admin Roles Membership Report

Manually reviewing the membership roster for each of the dozens of RBAC roles in a Microsft 365 tenant is quite the undertaking. Since this is something I need to keep an eye on, I decided to automate a report. Run the script, then look in your documents folder for the report.

$UserCredential = Get-Credential
Connect-AzureAD -Credential $UserCredential

$AzureADRoles = @(Get-AzureADDirectoryRole)

foreach ($AzureADRole in $AzureADRoles) {

    Write-Verbose “Processing $($AzureADRole.DisplayName)”

    #Get the list of members for the role
    $RoleMembers = @(Get-AzureADDirectoryRoleMember -ObjectId $AzureADRole.ObjectId)

    #Loop through the list of members
    foreach ($RoleMember in $RoleMembers) {
        $ObjectProperties = [Ordered]@{
            “Role” = $AzureADRole.DisplayName
            “Display Name” = $RoleMember.DisplayName
            “Object Type” = $RoleMember.ObjectType
            “Account Enabled” = $RoleMember.AccountEnabled
            “User Principal Name” = $RoleMember.UserPrincipalName
            “Password Policies” = $RoleMember.PasswordPolicies
            “HomePage” = $RoleMember.HomePage
        }

        $RoleMemberObject = New-Object -TypeName PSObject -Property $ObjectProperties

        #Add the role member’s details to the array for the report data
        [void]$O365AdminGroupReport.Add($RoleMemberObject)
    }
}

$O365AdminGroupReport | Export-CSV -Path $env:userprofile\documents\0365AdminGroupReport.csv -NoClobber -NoTypeInformation

PowerShell: Restore Soft Deleted Exchange On-line Mailbox To New Microsoft 365 User

Recently, I encountered a situation in which a Microsoft 365 account had been deleted. Then, a new account with the same name was created and synchronized from the local domain. The user’s local profile and other software were linked to the new account and everything was working. The only issue was the mailbox missing all of its content.

Believe it or not, this isn’t an uncommon situation in my line of work. I looked online for a script and found lots of examples. Much to my surprise, I struggled to get any of them to work. Rather than try to troubleshoot and fix one , I opted to write my own. While writing it, I believe I discovered the issue. Exchange Online does not except the ExchangeGUID as a name/value pair. It has to be plain text.

Below is what I came up with. You will need to have the Exchange Online PowerShell Module installed on your computer. Open an Admin PowerShell Session and run the one-liner below to install it. You may also be prompted to update PowerShell itself if your computer has fallen behind in updates.

Install-Module ExchangeOnlineManagement

Save and run the script below. First, it will prompt for the tenant’s modern authentication global admin credentials. Next, it will prompt you for the account your are working with’s identity. You should be able to use the first and last name, UPN, or alias address. The script will use that data to locate the Exchange GUID for the source and target mailboxes. Finally, it will create and run a mailbox restore request and show the status.

# Restore Soft Deleted Mailbox to a new Matching Account in Exchange Online
# Assumes the Alias for both accounts is the same

#Sign in to Microsoft 365 Exchange.
#Requires Microsoft Exchang Online PowerShell 
$GlobalAdminUPN = Read-Host "Enter Global Admin UPN account"
Connect-ExchangeOnline -UserPrincipalName $GlobalAdminUPN

#Aquire the ExchangeGUID attribute for the source and target mailboxes
$UserAlisas = Read-Host "Enter mailbox identifier"
$SourceMailboxGuid = [string](Get-Mailbox -SoftDeletedMailbox $UserAlisas).ExchangeGuid
$TargetMailboxGuid = [string](Get-Mailbox -Identity $UserAlisas).ExchangeGuid

#Restore Softdeleted mailbox over the new Account's mailbox

New-MailboxRestoreRequest -SourceMailbox $SourceMailboxGuid -TargetMailbox $TargetMailboxGuid -AllowLegacyDNMismatch

#Check the restore job status
Get-MailboxRestoreRequest | Get-MailboxRestoreRequestStatistics

PowerShell – Microsoft 365 User and Assigned Licenses Report

Microsoft 365 provides a lot of well conceived admin tools via its on-line portal. Their user tool is fantastic for creating and editing user accounts, but getting reports from it can be challenging. Lucky for us Microsoft 365 can also be accessed through PowerShell.

This script will prompt for credentials and the org name. Then it will retrieve all of the licensed users’ display names, primary smtp addresses from Exchange, user principle names, and the licenses currently applied to the account. The CSV report will be saved in your documents library.

The machine you run the script from needs the MS365 PowerShell modules installed. See https://docs.microsoft.com/en-us/office365/enterprise/powershell/connect-to-office-365-powershell

$UserCredential = Get-Credential
$ExchangeOnline = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $UserCredential -Authentication Basic -AllowRedirection
	Import-PSSession $ExchangeOnline
Connect-MsolService -Credential $UserCredential
$tenant = Read-Host "Enter Tenant Org Name"
$tenantname = $tenant + ":"

Get-MsolUser -All | Where {$_.islicensed -like "True"} | Select DisplayName, UserPrincipalName,
    @{Name="Primary Email Address"; Expression={Get-Mailbox -Identity $_.UserPrincipalName | Select-Object PrimarySmtpAddress -ExpandProperty PrimarySmtpAddress}},
    @{Name="Enabled Licenses"; Expression={[string]($_.Licenses.AccountSkuID).Replace("$tenantname", "     ") -replace "_", " "}}| 
    Export-Csv -Path $env:USERPROFILE\documents\Microsoft_365_User_Report.csv -NoTypeInformation    

Office 365 All-in-One PowerShell Management Console

If you administrate an Office 365 tenant, you’ve undoubtedly discovered that PowerShell is a requirement rather than an option. Using PowerShell with Office 365 isn’t all that different from the on-premises version, but connecting to all the services can be challenging. Often, a task or project requires multiple modules to function.

With a little scripting knowledge we can connect to and manage all of the O365 services at once. I can’t tell you how many times I got half-way through a project only to realize that I didn’t have all the required cmdlets. Logging on to everything each time I use PowerShell saves time and frustration.

To make the code below work, install the PowerShell modules each service requires. Open an elevated PowerShell console (right click, run as administrator). Check the execution policy (Get-ExecutionPolicy), if it is restricted use the following command to change that: Set-ExeuctionPolicy -ExecutionPolicy Unrestricted . Then use the following commands to install all of the tools:

  • Install-Module AzureAD
    • Type A and press Enter (yes to all) when prompted.
  •  Install-Module MSOnline
    • Type A and press Enter (yes to all) when prompted.
  • Install-Module MicrosoftTeams
    • Type A and press Enter (yes to all) when prompted.
  • Install-Module Microsoft.SharePoint.Online.PowerShell
    • Type A and press Enter (yes to all) when prompted.

Copy the code below and save it as a PS1 file named Manage-O365.PS1 in your documents folder. Make a new desktop shortcut with the following path: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -NoExit “C:\Users\profile\Documents\Manage-O365.ps1” . When you double-click it you’ll be prompted for credentials and the Office 365 organization name. After entering them, a PowerShell console will launch and connect to O365 services. The window stays open until you are done with your tasks.

$UserCredential = Get-Credential
$OrgName = Read-Host "Enter the Name of your Office 365 Organization, Example: Techbloggingfool"
	$ExchangeOnline = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $UserCredential -Authentication Basic -AllowRedirection
		Import-PSSession $ExchangeOnline
	Connect-MsolService -Credential $UserCredential
	Connect-AzureAD -Credential $UserCredential
	Connect-MicrosoftTeams -Credential $UserCredential
	Connect-SPOService -Url https://$OrgName-admin.sharepoint.com -Credential $UserCredential

Tip: Save these lines as a snippet in your favorite IDE (Visual Code, ISE, etc.) and you can easily insert them for Office 365 scripting projects.