PowerShell
Microsoft 365 PowerShell scripting is a powerful tool for automating and managing various aspects of the Microsoft 365 environment. With PowerShell, IT professionals can streamline administrative tasks, enhance operational efficiency, and ensure consistent configurations across the organization.
8/1/20205 min read
PowerShell
Modify Mailbox Settings Via the Set-Mailbox Cmdlet
Set-Mailbox -Identity "Joseph Ludwig" -Alias "Josephludwig25"
Set-Mailbox -Identity “Joseph Ludwig” -DisplayName “Joe Ludwig”
Set-Mailbox -Identity “Joseph Ludwig” -samAccountName joeludwig
Set-Mailbox -Identity “Joseph Ludwig” -ArchiveDatabase Archive01
Set-Mailbox -Identity “Joseph Ludwig” -Database MBX01Archive01
Set-Mailbox -Identity “Joseph Ludwig” -ArchiveQuota 50GB
Set-Mailbox -Identity “Joseph Ludwig” -ArchiveWarningQuota 45GB
Set-Mailbox -Identity “Joseph Ludwig” -ForwardingAddress “Joseph Ludwig”
Set-Mailbox -Identity “Joseph Ludwig” -ForwardingSmtpAddress “josephludwig@gmail.com”
Set-Mailbox -Identity “Joseph Ludwig” -ForwardingAddress “Joseph Ludwig” -DeliverToMailBoxAndForward $True
Get-AdUser -Filter {department eq 'IT'} | ForEach {Set-Mailbox -Identity $_.Name -DeliverToMailboxAndForward $true -ForwardingAddress "Joseph Ludwig"}
Get-ADUser -SearchBase "OU=IT,OU=Department,DC=jl,DC=joe,DC=com" -Properties -Filter | Select samAccountName,GivenName,Surname,DisplayName,UserPrincipalName,EmailAddress,Department,msExchRecipientTypeDetails,Title,Company,Enabled,LastLogonDate,PasswordLastSet,PasswordNeverExpires | Export-Csv C:\Users\joe\Desktop\HR10102024.csv -Encoding UTF8 -NoTypeInformation
Sharepoint Cmdlet
Get-SPOTenant | Select disallowinfectedfiledownload
Set-SPOTenant -DisallowInfectedFileDownload $true
Office 365 Tenant Cmdlet
New-AuthenticationPolicy -Name "Block Basic Authentication"
Set-OrganizationConfig -MailTipsExternalRecipientsTipsEnabled $True
Set-OwaMailboxPolicy OwaMailboxPolicy-Default -LinkedInEnabled $False
Set-OwaMailboxPolicy OwaMailboxPolicy-Default -AdditionalStorageProvidersAvailable $False
Set-AdminAuditLogConfig $true
Get-MsolcompanyInformation | Select Allowemailverifiedusers, Allowadhocsubscriptions
Get-OrganizationConfig | fl auditdisabled*
Disable Mailbox
Disable-Mailbox it@josephludwig.com
Delete mailbox
Remove-Mailbox it@josephludwig.com
Verify Deleted Mailbox
$dbs = Get-MailboxDatabase
$dbs | foreach {Get-MailboxStatistics -Database $_.DistinguishedName} | where {$_.DisplayName -eq "<DisplayName>"} | Format-List DisconnectReason,DisconnectDate
Reconnect deleted Mailbox
New-MailboxRestoreRequest -SourceStoreMailbox e4890ee7-79a2-4f94-9569-91e61eac372b -SourceDatabase MBXDB01 -TargetMailbox "Joe Ludwig" -AllowLegacyDNMismatch
Get-User -Identity it@josephludwig.com
Connnect Mailbox:
Connect-Mailbox -Identity "Joseph Ludwig" -Database MBXDB02 -LinkedDomainController DC01 -LinkedMasterAccount it@josephludwig.com -Alias joeludwig
Enable Audit Log:
Set-AdminAuditLogConfig -UnifiedAuditLogIngestionEnabled $true
Get-AdminAuditLogConfig | Format-List UnifiedAuditLogIngestionEnabled
Set-AdminAuditLogConfig -UnifiedAuditLogIngestionEnabled $false
One Drive Provisioning
Install-Module Microsoft.Online.SharePoint.PowerShell -Force
Connect-SPOService -Url https://domain-admin.sharepoint.com
$emails = "joe1@contoso.com", "joe2@contoso.com"
Request-SPOPersonalSite -UserEmails $emails -NoWait
Enable Archive Mailbox (PowerShell command to automatically provision an archive mailbox when a primary mailbox that's licensed for archiving reaches 90% of the quota )
Enable-Organizationcustomization
Set-OrganizationConfig -AutoEnableArchiveMailbox $true
Enable for All
Get-Mailbox -Filter {ArchiveGuid -Eq "00000000-0000-0000-0000-000000000000" -AND DisabledArchiveGuid -Eq "00000000-0000-0000-0000-000000000000" -AND RecipientTypeDetails -Eq "UserMailbox"} | Enable-Mailbox -Archive
Enable for users doesn’t have archive mailbox enabled
Get-Mailbox -Filter {ArchiveStatus -Eq "None" -AND RecipientTypeDetails -eq "UserMailbox"} | Enable-Mailbox -Archive
Enable for Single User
Enable-Mailbox -Identity <username> -Archive
Disable Archive Mailbox
Disable-Mailbox -Identity <username> -Archive
Disable for All
Get-Mailbox -Filter {ArchiveGuid -Ne "00000000-0000-0000-0000-000000000000" -AND RecipientTypeDetails -Eq "UserMailbox"} | Disable-Mailbox -Archive
Autoexpand Archive for Org
Set-OrganizationConfig -AutoExpandingArchive
Get-OrganizationConfig | FL AutoExpandingArchiveEnabled
Expand Auto Archive for Single User
Enable-Mailbox <user mailbox> -AutoExpandingArchive
Get-Mailbox <user mailbox> | FL AutoExpandingArchiveEnabled
Disable-Mailbox -Identity "joseph.ludwig@josephludwig.com" -Confirm:$false
With CSV
Identity
john.doe@ josephludwig.com
Import-Csv -Path "C:\Path\To\mailboxes.csv" | ForEach-Object {
Disable-Mailbox -Identity $_.Identity -Confirm:$false
}
Without CSV
$mailboxes = @(
"jane.smith@josephludwig.com",
)
foreach ($mailbox in $mailboxes) {
Disable-Mailbox -Identity $mailbox -Confirm:$false
}
Get-Mailbox -InactiveMailboxOnly | FL UserPrincipalName,AutoExpandingArchiveEnabled
Outlook Registry Key to Configure Outlook for On Prem user without connecting to office 365 when organization is in hybrid mode.
reg add HKEY_CURRENT_USER\Software\Policies\Microsoft\Office\16.0\Outlook\AutoDiscover /v ExcludeExplicitO365Endpoint /t REG_DWORD /d 1 /f
Single User:
Set-MailboxCalendarConfiguration -Identity Joseph.ludwig@jl.com -WorkingHoursStartTime "09:00:00" -WorkingHoursEndTime "17:00:00"
All Users
Connect-ExchangeOnline
$users = Get-Mailbox -ResultSize Unlimited
foreach ($user in $users) {
Set-MailboxCalendarConfiguration -Identity $user.UserPrincipalName -WorkingHoursStartTime "09:00:00" -WorkingHoursEndTime "17:00:00"
}
Connect MG Graph:
Connect-MgGraph -Scopes "User.Read.All", "Group.ReadWrite.All" -UseDeviceAuthentication
Connect EXO
connect-exchangeonline -DisableWAM
USER:
Get-User -ResultSize Unlimited | Export-Csv "C:\Users\jl\Documents\Users_Report13072026.csv" -NoTypeInformation -Encoding UTF8
Get-UnifiedGroup | Select-Object * | Export-Csv "C:\Users\jl\Documents\M365Group_Report13072026.csv" -NoTypeInformation -Encoding UTF8
Get-Mailbox -ResultSize Unlimited | Export-Csv "C:\Users\jl\Documents\Mailbox_Report13072026.csv"
Update-MgUser -UserId "olduser@old-domain.com" -UserPrincipalName "newuser@new-domain.com"
Set-Mailbox -Identity "user@old-domain.com" -EmailAddresses @{add="smtp:user@old-domain.com"} -PrimarySmtpAddress "user@new-domain.com"
Set-Mailbox -Identity "sari@josephludwig.onmicrosoft.com" -EmailAddresses @{add=smtp:sari@josephludwig.onmicrosoft.com} -PrimarySmtpAddress "sari@josephludwig.com"
Add-MailboxFolderPermission -Identity jl@abcd.ae:\Calendar -User aai@josephludwig.com -AccessRights Reviewer
Set-Mailbox -Identity "sharedmailbox@josephludwig.com" -MessageCopyForSentAsEnabled $true -MessageCopyForSendOnBehalfEnabled $true
Get-Mailbox -ResultSize Unlimited -RecipientTypeDetails "SharedMailbox" | Set-Mailbox -MessageCopyForSentAsEnabled $true -MessageCopyForSendOnBehalfEnabled $true
Get-Mailbox -Identity "sharedmailbox@josephludwig.com" | Select-Object MessageCopyForSentAsEnabled, MessageCopyForSendOnBehalfEnabled
Start-ManagedFolderAssistant -Identity "alias@josephludwig.com"
Get-User -ResultSize Unlimited | Export-Csv "C:\Users\josephludwig\Documents\nsb\Users_Report.csv" -NoTypeInformation -Encoding UTF8
USER CREATION:
New-Mailbox `
-Name "nithin" `
-MicrosoftOnlineServicesID "nithin@testm365learning.onmicrosoft.com" `
-Password (ConvertTo-SecureString "P@ssw0rd123" -AsPlainText -Force) `
-FirstName "nithin" `
-LastName "kumar" `
-DisplayName "Nithin Kumar" `
-ResetPasswordOnNextLogon $true
GROUP:
Get-UnifiedGroup | Select-Object * | Export-Csv "C:\Users\josephludwig\Documents\nsb\M365Groups.csv" -NoTypeInformation -Encoding UTF8
SHAREDMAILBOX:
Get-EXOMailbox -Identity "SharedMailboxNameOrEmail" -PropertySets All | Format-List *
Get-EXOMailbox -RecipientTypeDetails SharedMailbox -PropertySets All | Format-List *
LICENSE:
Set-MgUserLicense -UserId "username@domain.com" -AddLicenses @{SkuId = "SPE_E5.SkuId", DisabledPlans = @() } -RemoveLicenses @()
LICENSE ADD AND REMOVE:
ADD:
Set-MgUserLicense -UserId john.doe@domain.com -AddLicenses @{SkuId = "6c933073-e02b-4a67-b80f-d733735a2ba2"}
REMOVE:
Set-MgUserLicense -UserId john.doe@domain.com -RemoveLicenses @{SkuId = "6c933073-e02b-4a67-b80f-d733735a2ba2"}
CHANGE UPN AND SMTP:
SMTP:
Set-Mailbox -Identity "user@old-domain.com" `
-EmailAddresses @{add="smtp:user@old-domain.com"; remove="SMTP:user@old-domain.com"} `
-PrimarySmtpAddress "user@new-domain.com"
UPN:
Update-MgUser -UserId "olduser@old-domain.com" -UserPrincipalName "newuser@new-domain.com"
SHAREPOINT:
Connect-SPOService -Url "https://testm365learning-admin.sharepoint.com"; Get-SPOSite -Limit All | Export-Csv "C:\Users\joeludwig\Documents\nsb\SharePointSites.csv" -NoTypeInformation -Encoding UTF8
PASSWORD RESET:
Update-MgUser -UserId "user@domain.com" `
-PasswordProfile @{
Password = "NewStrongP@ssw0rd!"
ForceChangePasswordNextSignIn = $true
}
ONEDRIVE PROVISIONING:
Connect-SPOService -Url "https://testm365learning-admin.sharepoint.com"
Request-SPOPersonalSite -UserEmails <UserPrincipalName> -NoWait
SET PRIMARY/SECONDARY SMTP:
pntity "user@domain.com" -EmailAddresses "SMTP:newprimary@domain.com","smtp:alias@domain.com"
AD
USER CREATION:
New-Mailbox -Name "John Doe" -Alias jdoe -UserPrincipalName john.doe@contoso.com -FirstName John -LastName Doe -DisplayName "John Doe" -OrganizationalUnit "OU=Users,DC=contoso,DC=com" -Password (ConvertTo-SecureString "P@ssw0rd123!" -AsPlainText -Force)
CHANGE UPN:
Import-Module ActiveDirectory
Set-ADUser -Identity "samAccountName_or_CN" -UserPrincipalName "newusername@yourdomain.com"
SET PRIMARY/SECONDARY SMTP:
Set-Mailbox -Identity "user@domain.com" -EmailAddresses "SMTP:newprimary@domain.com","smtp:alias@domain.com"
CREATE SECURITY GROUP:
New-ADGroup -Name "Sales" -SamAccountName "Sales" -GroupCategory Security -GroupScope Global -Path "OU=Groups,DC=contoso,DC=com"
CREATE DL GROUP:
New-ADGroup -Name "Marketing" -SamAccountName "Marketing" -GroupCategory Distribution -GroupScope Global -Path "OU=Groups,DC=contoso,DC=com"
PASSWORD RESET:
Set-ADAccountPassword -Identity "jdoe" -NewPassword (ConvertTo-SecureString "NewP@ssw0rd123!" -AsPlainText -Force) -Reset; Set-ADUser -Identity "jdoe" -ChangePasswordAtLogon $true
EZP-SG-CA-PwdMFA-Users
Add-MailboxFolderPermission -Identity amal.albraiki@erthzayed.ae:\Calendar -User alreem.alameri@josephludwig.com -AccessRights Reviewer
Set-Mailbox -Identity "sharedmailbox@josephludwig.com" -MessageCopyForSentAsEnabled $true -MessageCopyForSendOnBehalfEnabled $true
Get-Mailbox -ResultSize Unlimited -RecipientTypeDetails "SharedMailbox" | Set-Mailbox -MessageCopyForSentAsEnabled $true -MessageCopyForSendOnBehalfEnabled $true
Get-Mailbox -Identity "sharedmailbox@josephludwig.com" | Select-Object MessageCopyForSentAsEnabled, MessageCopyForSendOnBehalfEnabled
Start-ManagedFolderAssistant -Identity "alias@josephludwig.com"
One Note Locations Backup Locations
Local Backups: Found at C:\Users\<username>\AppData\Local\Microsoft\OneNote\<version>\Backup.
Classic Local Notebooks: Located at C:\Users\<username>\Documents\OneNote
Get-Mailbox -RecipientTypeDetails RoomMailbox | Set-CalendarProcessing -AddOrganizerToSubject $false -DeleteSubject $false -DeleteComments $false -RemovePrivateProperty $false
Set-CalendarProcessing MeetingRoom@jl.com -AddOrganizerToSubject $false -DeleteSubject $false -DeleteComments $false -RemovePrivateProperty $false
Connect to SharePoint
Install-Module -Name Microsoft.Online.SharePoint.PowerShell
Import-Module Microsoft.Online.SharePoint.PowerShell -UseWindowsPowerShell
Connect-SPOService -Url https://erthzayedphilanthropies-admin.sharepoint.com
Connect-SPOService -Url "https://yourtenant-admin.sharepoint.com" -ModernAuth $true
Create Template Library
https://learn.microsoft.com/en-us/sharepoint/organization-assets-library
Create a dedicated SharePoint Communication Site (e.g., https://sharepoint.com).Create a standard Document Library inside that site named Word Templates.Ensure the library permissions grant Read/Visitor access to "Everyone except external users" so all employees can view the files.
# 1. Define Variables
$AdminUrl = "https://sharepoint.com"
$LibraryUrl = "https://sharepoint.com Templates"
# Optional: Add a custom thumbnail logo (PNG/JPG) for the organization tab in Office
$ThumbnailUrl = "https://sharepoint.com"
# 2. Connect to SharePoint Online Admin Center
Connect-SPOService -Url $AdminUrl
Get-SPOOrgAssetsLibrary
PS C:\Users\jl> Get-SPOOrgAssetsLibrary
No libraries have been specified as organization asset libraries.
Add-SPOOrgAssetsLibrary -LibraryURL "https://josephludwig.sharepoint.com/Word Templates" -OrgAssetType OfficeTemplateLibrary -CdnType Private
WARNING: Enabling this feature will turn on a content delivery network (CDN) for this tenant to provide fast and reliable performance for shared assets. The CDN may have privacy and compliance standards that differ from the commitments and compliance boundaries outlined by the Microsoft Office365 Trust Center, and data cached through this service may not conform to the Microsoft Data Processing Terms (DPT). For more information on CDNs, see:https://go.microsoft.com/fwlink/?linkid=2077392
WARNING: Enabling the CDN for Organizational Assets will also enable the default origins of the chosen CDN. Should you wish to exclude the default locations, then please use the -NoDefaultOrigins option
Confirm
Are you sure you want to perform this action?
Performing the operation "Enable Tenant CDN with the default locations" on target "Private CDN".
[Y] Yes [A] Yes to All [N] No [L] No to All [?] Help (default is "Y"): a
Document library added successfully.
PS C:\Users\jpeter> Get-SPOOrgAssetsLibrary
SMTP Authentication:
Set-CASMailbox -Identity scantoprint@jl.com -SmtpClientAuthenticationDisabled $false
Get-TransportConfig | Select SmtpClientAuthenticationDisabled
