Category Archives: PowerShell

How to recover data from a Deleted or Inactive mailbox in Exchange Online

The default mailbox retention in Microsoft 365 is 30 days, we can recover deleted/Inactive user’s mailbox to a new user or to a temporary user.

Please note that if you remove license form a user, mailbox will also be removed, once we reassign the license, mailbox will reconnect automatically.

To list all the deleted mailboxes

Get-Mailbox -SoftDeletedMailbox | select DisplayName, PrimarySmtpAddress, WhenSoftDeleted, RecipientTypeDetails, GUID, CustomAttribute6, DistinguishedName

#You can export this list in CSV.
Get-Mailbox -SoftDeletedMailbox | select DisplayName, PrimarySmtpAddress, WhenSoftDeleted, RecipientTypeDetails, GUID, CustomAttribute6, DistinguishedName | Export-Csv C:\Temp\Deletedmailboxes.csv -NoTypeInformation 

#In the output file we can find the mailbox information we want to recover.

We can also find just one mailbox from deleted mailboxes.

Get-Mailbox -SoftDeletedMailbox -Filter {name -like "*Mailbox Name*"} | fl Guid, DistinguishedName

Note down the mailbox GUID from above command and run below commands to restore the mailbox.

#Get details of inactive mailbox
$InactiveMailbox = Get-Mailbox -SoftDeletedMailbox -Identity 532f8e25-b435-4a17-b253-9097632680a1
#Run restore command
New-MailboxRestoreRequest -Name UserName-Restore -SourceMailbox $InactiveMailbox.DistinguishedName -TargetMailbox <DN of TargetMailbox> -TargetRootFolder Restore -AllowLegacyDNMismatch

Now, you can trace the restore using below command

#To get all the restore request.
Get-MailboxRestoreRequest  | Get-MailboxRestoreRequestStatistics

#To get just one restore request.
Get-MailboxRestoreRequestStatistics -Identity RestoreRequest

Get list of users created in AD within last few days

Using PowerShell we can get list of users created during a particular time frame, like in last 1 day, 30 days, etc. This may be helpful in AD audit or to track any security breach.

First, create a variable and store the date you want to go back.

Make sure you run the PowerShell as Admin, if you don’t you may get blank values for WhenCreated

$When = (Get-Date).AddDays(-30) # You can change number of days here as per your requirement. 
Get-ADUser -Filter {WhenCreated -ge $when}

#IF you want to list particular properties, you can use below command.
Get-ADUser -Filter {WhenCreated -ge $when} -Properties * | FT Name, UserPrincipalName, WhenCreated

We can also get group membership of these users in same command output.

Get-ADUser -Filter {whenCreated -ge $when} -Properties * | select UserPrincipalname, SamAccountName, Enabled, whenCreated, @{n="GroupMembership"; e={$_.MemberOf | foreach {(Get-ADGroup $_).Name}}}

Export this list to CSV file.

Get-ADUser -Filter {whenCreated -ge $when} -Properties * | select UserPrincipalname, SamAccountName, Enabled, whenCreated, @{n="GroupMembership"; e={$_.MemberOf | foreach {(Get-ADGroup $_).Name}}} | Export-CSV C:\Temp\ADUsersWhenCreated.csv -notype

Update Room and Equipment Mailboxes features using the Resource Schema

When creating room mailboxes, it is good to show features of room mailbox to end users for easy identification.

By default in GAL description will only show “Room” which may not be sufficient to identify capabilities of Room while booking.

For example, we can update details like TVScreen, whiteboard, Smartboard with room.

Using resouce schema we can update all features of a room mailbox.

#To check current resource config
Get-ResourceConfig

We can add resource schema using below commands.

Set-ResourceConfig -ResourcePropertySchema @{add="Room/WithTVScreen"}
Set-ResourceConfig -ResourcePropertySchema @{add="Room/Whiteboards"}

Adding resource config value will not update any mailbox, but we will have to set these configs on room mailboxes.

If a item is not there in resource config, you can’t add that item on room mailbox.

Also, only a alphanumeric value is allowed and space is not allowed.

Set-Mailbox R_BoardRoom -ResourceCustom   @{add= "WithTVScreen"}
Set-Mailbox R_PinkRoom -ResourceCustom  @{add= "WithTVScreen", "Whiteboards"}
Set-Mailbox R_SmartRoom -ResourceCustom  @{add= "WithTVScreen", "Whiteboards", "VideoConf" }

Once you update and download the GAL, you will see below results.

Add members to Azure AD/Microsoft 365 Groups in bulk

We can bulk update Microsoft 365/Azure AD Groups using PowerShell. We just need a list of users UPN or primary SMTP Addresses.

Get the group’s object ID.

You can copy the group’s object ID from Azure AD console from properties tab or use below command.

#Connect Azure AD
Connect-AzureAD
(Get-AzureADGroup -SearchString Test-Group).ObjectId

If you want to add a mailbox to the group, use below command, it will add User@domain.com to Test-Group

#Connect Azure AD and Exchange online if not connected already. 
Connect-AzureAD
Connect-ExchangeOnline -UserPrincipalName <Your O365 Admin ID>

Add-AzureADGroupMember -ObjectId <Group's Object ID> -RefObjectId (Get-Mailbox User@domain.com).ExternalDirectoryObjectId

If you want to add a set of Azure AD users, for example all users start with TestUser, below command will add all the users start with TestUser to TestGroup

Get-AzureADUser -SearchString TestUser | foreach {Add-AzureADGroupMember -ObjectId <Gorup's ObjectID> -RefObjectId $_.ObjectID}

If you have a list of users, create a file Userlist.txt [One UPN or email per line] and save in C:\Temp folder. Below command will add all the users mentioned in Userlist.txt to the Test-Group

#Connect Azure AD and Exchange online if not connected already.
Connect-AzureAD
Connect-ExchangeOnline -UserPrincipalName <Your Microsoft 365 Admin ID>
Get-Content C:\Temp\UserList.txt | foreach {Add-AzureADGroupMember -ObjectId <Group's Object ID> -RefObjectId (Get-Mailbox $_).ExternalDirectoryObjectId}

Add Microsoft 365 licenses in bulk

We can add bulk license to Microsoft 365 users using Microsoft 365 PowerShell, though it is always good to create a Dynamic group for license assignment. But, we can have situation when we want to add licenses to some users who already have other license assigned and doesn’t have any common attribute to create and add new license.

For Example, you have new “Phone System” license and want to add that license to selected users for testing or for UAT.

If user doesn’t have any license and we are adding license for first time, then we will have to set location first.

Step 1 –

Get list of users and save in a file “UserList.txt”, one UPN per line and place in C:\Temp folder on your computer.

The below command will set location on all users mentioned in “UserList.txt” to US.

Connect-MsolService

#When prompted enter your Microsoft 365 Admins accounts UPN and password.

Get-Content C:\Temp\UserList.txt | foreach {Get-MsolUser -UserPrincipalName $_ | Set-MsolUser -UsageLocation US}

If users are being synced from On-prem AD, you can set msExchUsageLocation on on-prem AD users and wait for the Sync to complete.

Run below command on your On-Prem AD server.

Get-Content C:\Temp\UserList.txt | foreach {Get-ADUser -Filter {UserPrincipalName -eq $_ | Set-ADUser -Add @{msExchUsageLocation = "US" }

Step 2 –

Get the SkuPartNumber of the license you want to add to users.

Connect-AzureAD

#When prompted enter your Microsoft 365 Admins accounts UPN and password.

Get-AzureADSubscribedSku | Select Sku*, ConsumedUnits

Note down the license Sku number to use in next command. For example for “Phone System” SkuPartNumber is MCOEV.

Step 3 –

The below command will add “PhoneSystem” license to all users and there would not be any change in existing license.

Get-Content C:\Temp\UserList.txt  | foreach { Write-Host "Processing $_";  Set-MsolUserLicense -UserPrincipalName $_  -AddLicenses "YourTenantname:MCOEV" }

Get Distribution Group Owner lists and email

User below PowerShell one liner we can list group owners and their email ID in Microsoft 365.

To get for one group.

Get-DistributionGroup TestGroup@Domain.com | select PrimarySmtpAddress, @{n= "ManagedBy"; e={$_.ManagedBy | foreach {(Get-Mailbox $_).PrimarySMTPAddress}}}

To get for all groups

Get-DistributionGroup | select PrimarySmtpAddress, @{n= "ManagedBy"; e={$_.ManagedBy | foreach {(Get-Mailbox $_).PrimarySMTPAddress}}}

We can also filter groups and get the list. Below command will list all the groups starting with DL-IT

Get-DistributionGroup DL-IT* | select PrimarySmtpAddress, @{n= "ManagedBy"; e={$_.ManagedBy | foreach {(Get-Mailbox $_).PrimarySMTPAddress}}}

List Users from BookInPolicy on a room mailbox.

We can use below command to get the list of users from BookInPolicy on a resource mailbox.

Get-CalendarProcessing User@domain.com | select -ExpandProperty BookInPolicy | Get-Recipient | select PrimarySmtpAddress, RecipientType

If you have multiple Room Mailboxes to check, you can use below script.

Save all room mailbox in RoomMailbox.txt [One mailbox per line] and run the below command.

$RoomList = Get-Content C:\Temp\RoomMailbox.txt
Foreach ($room in $RoomList)
{
#$BookInPolicy = 0
$BookInPolicy = Get-CalendarProcessing $room | select -ExpandProperty BookInPolicy | Get-Recipient | select PrimarySmtpAddress, RecipientType
Write-Host "Room $room has below users"
$BookInPolicy
Write-Host "        "
Write-Host "........"
}

View members of a dynamic distribution group

Dynamic distribution groups are distribution groups whose membership is based on specific recipient filters rather than a defined set of recipients.
You can’t use the Exchange admin center (EAC) to view the members of a dynamic distribution group. You can only use the Exchange Management Shell.

Using below command you can get list of members.

Get-Recipient -RecipientPreviewFilter (Get-DynamicDistributionGroup -Identity DDL@domain.com).RecipientFilter

Using below command you can get list of members and their DisplayName and PrimarySMTPAddresses, you can also specify any attribute to select.

Get-Recipient -RecipientPreviewFilter (Get-DynamicDistributionGroup -Identity DDL@domain.com).RecipientFilter | foreach {Get-Mailbox $_.PrimarySMTPAddress | select DisplayName, PrimarySMTPAddress}