Listen to this Post

Introduction:
In the complex ecosystem of Microsoft 365, manual administration is not just tedious—it’s a security risk. Automating routine tasks with PowerShell is the definitive strategy for enhancing operational efficiency and enforcing a robust security posture. This guide delves into a curated collection of over 50 essential PowerShell scripts, transforming how admins manage licenses, users, data, and threats.
Learning Objectives:
- Automate critical user and license lifecycle management to reduce human error and overhead.
- Implement advanced auditing and security monitoring to detect and respond to threats proactively.
- Master the management of Exchange Online, Microsoft Teams, and SharePoint through precise scripting.
You Should Know:
1. Automating User Account and License Lifecycle Management
Efficiently managing users from onboarding to offboarding is fundamental to security and compliance. Manual processes are prone to errors, such as leaving accounts active after termination or misassigning licenses, which can create security gaps and unnecessary costs.
Step-by-step guide:
Prerequisite: Connect to the MS Online service and the Exchange Online module.
Connect to Microsoft Online Connect-MsolService Connect to Exchange Online Connect-ExchangeOnline -UserPrincipalName [email protected]
Create a New User and Assign a License: This script creates a user, sets their location, and assigns a license.
Define user parameters $DisplayName = "John Doe" $UserPrincipalName = "[email protected]" $License = "yourdomain:ENTERPRISEPACK" E3 license $Password = ConvertTo-SecureString "TempPassword123!" -AsPlainText -Force Create the new user New-MsolUser -DisplayName $DisplayName -UserPrincipalName $UserPrincipalName -UsageLocation "US" -LicenseAssignment $License -Password $Password -ForceChangePassword $True
Disable a User and Block Sign-In: For secure offboarding.
Block sign-in and convert mailbox to shared Set-MsolUser -UserPrincipalName "[email protected]" -BlockCredential $True Set-Mailbox -Identity "[email protected]" -Type Shared
2. Advanced Exchange Online Auditing and Security
Proactive monitoring of email flow and mailbox activities is crucial for detecting phishing campaigns, data exfiltration attempts, and internal threats. PowerShell provides unparalleled depth for these investigations.
Step-by-step guide:
Prerequisite: Ensure you have the `ExchangeOnlineManagement` module and the necessary permissions (e.g., Audit Logs, Compliance Search).
Search for Messages with Specific Malicious Attachments: Hunt for potential threats.
Search-UnifiedAuditLog -StartDate (Get-Date).AddDays(-7) -EndDate (Get-Date) -Operations "MailItemsAccessed" -ResultSize 5000 | Where-Object {$<em>.AuditData -like "malicious.pdf"}
Get Mailbox Forwarding Rules: Identify auto-forwarding rules that could be exfiltrating data.
Get-Mailbox | Get-InboxRule | Where-Object {$</em>.RedirectTo -ne $null -or $<em>.ForwardTo -ne $null} | Select-Object MailboxOwnerId, Name, RedirectTo, ForwardTo
Generate a Report of Large Item Deletions: A potential indicator of a compromised account or malicious insider.
Search-UnifiedAuditLog -Operations "SoftDelete, HardDelete" -ResultSize 5000 | Where-Object {$</em>.AuditData -like """Size>"} | Export-Csv "C:\temp\LargeDeletions.csv" -NoTypeInformation
3. Securing Microsoft Teams and SharePoint Online Configurations
Misconfigurations in collaboration platforms are a primary attack vector. Automating the audit and hardening of Teams and SharePoint settings is essential for a Zero-Trust approach.
Step-by-step guide:
Prerequisite: Connect to Microsoft Teams and SharePoint Online PnP.
Connect to Microsoft Teams Connect-MicrosoftTeams Connect to SharePoint Online Connect-PnPOnline -Url https://yourdomain-admin.sharepoint.com -Interactive
Audit Teams for External Sharing: Identify teams that allow guest access.
Get-Team | ForEach-Object {
$team = $_
$group = Get-UnifiedGroup -Identity $team.GroupId
[bash]@{
TeamName = $team.DisplayName
ExternalSharingEnabled = $group.AllowAddGuests
}
} | Where-Object {$_.ExternalSharingEnabled -eq $True}
Disable External Sharing on a Specific SharePoint Site:
Set-PnPTenantSite -Url https://yourdomain.sharepoint.com/sites/yoursite -SharingCapability Disabled
4. Comprehensive Guest and External User Management
External collaborators are a necessary part of business but expand your attack surface. Gaining visibility and control over their access and activities is a non-negotiable security practice.
Step-by-step guide:
Generate a Report of All Guest Users and Their Access:
Get-MsolUser -All -UserType Guest | Select-Object DisplayName, UserPrincipalName, WhenCreated, BlockCredential | Export-Csv "C:\temp\GuestUsers.csv" -NoTypeInformation
Remove a Specific Guest User from the Directory:
Remove-MsolUser -UserPrincipalName "[email protected]" -Force
5. Proactive Security Health Checks and Alerts
Moving from a reactive to a proactive security stance requires continuous monitoring of your M365 security score and critical settings. Automate these checks to catch drift and new vulnerabilities.
Step-by-step guide:
Check for Users Who Haven’t Enforced MFA: (Note: The `MfaStatus` property can be complex; this checks for non-compliant methods).
Get-MsolUser -All | Where-Object {$<em>.StrongAuthenticationRequirements.State -ne "Enforced"} | Select-Object DisplayName, UserPrincipalName, StrongAuthenticationRequirements
Get a Report of Admin Accounts: Continuously monitor privileged access.
Get-MsolRole | ForEach-Object {
$role = $</em>.Name
Get-MsolRoleMember -RoleObjectId $_.ObjectId | Select-Object @{Name="Role"; Expression={$role}}, DisplayName, EmailAddress, IsLicensed
} | Export-Csv "C:\temp\AdminAccounts.csv" -NoTypeInformation
What Undercode Say:
- Automation is Your First Line of Defense: Manual administrative tasks are the weakest link, susceptible to fatigue and error. Scripting these processes enforces consistency, creates an audit trail, and drastically reduces the attack surface.
- Visibility Equals Control: The true power of these scripts lies not just in doing, but in discovering. They provide deep, queryable insights into your environment’s configuration and user behavior, enabling you to move from a reactive to a predictive security posture. Relying solely on the GUI is like navigating a complex network in the dark; these scripts flip the light switch on, revealing misconfigurations, stale accounts, and anomalous activities that would otherwise go unnoticed until a breach occurs.
Prediction:
The role of the M365 admin will evolve from a manual configuration manager to an automation architect and security analyst. As AI-driven attacks become more sophisticated, the manual review of logs and settings will be entirely obsolete. Future security frameworks will rely entirely on AI-powered scripts and automated playbooks that not only identify threats but also execute immediate, predefined mitigation actions—such as automatically isolating compromised users, revoking suspicious session tokens, or rolling back malicious configuration changes—all within seconds of detection. The admins who master PowerShell scripting today are building the foundational skills to command these advanced, autonomous security systems tomorrow.
🎯Let’s Practice For Free:
IT/Security Reporter URL:
Reported By: Kavya A – Hackers Feeds
Extra Hub: Undercode MoN
Basic Verification: Pass ✅


