A PowerShell function is a reusable block of code designed to perform a specific task. It allows you to encapsulate logic into a named procedure, which can be called multiple times throughout your script. Functions help improve readability, modularity, and maintainability of scripts—especially in automation-heavy environments like Microsoft 365 administration.
Functions can accept parameters, return values, and include conditional logic, loops, or even other function calls.
The basic syntax for defining a function in PowerShell is:
function FunctionName {
param ([type]$parameter1, [type]$parameter2)
# Code block
}
Functions are particularly useful for recurring tasks—like creating users, assigning licenses, or sending reports—because you can define the task once and reuse it as needed.
Here’s a PowerShell function that creates a new Microsoft 365 user when provided with a UserPrincipalName (UPN):
function Create-M365User {
param (
[Parameter(Mandatory=$true)]
[string]$UserPrincipalName
)
# Extract username part before '@'
$NamePart = $UserPrincipalName.Split('@')[0]
# Convert to Title Case for DisplayName
$DisplayName = -join ($NamePart -split '\.?' | ForEach-Object { $_.Substring(0,1).ToUpper() + $_.Substring(1).ToLower() })
# MailNickname is same as NamePart (no domain)
$MailNickname = $NamePart
# Create the user
New-MgUser -UserPrincipalName $UserPrincipalName `
-DisplayName $DisplayName `
-MailNickname $MailNickname `
-AccountEnabled `
-PasswordProfile @{
ForceChangePasswordNextSignIn = $true
Password = "TempP@ssw0rd!"
}
}
Create-M365User -UserPrincipalName "alex.ryan@yourtenant.com"
🔄 Tip: PowerShell functions are best defined and executed within scripts saved as .ps1 files for consistent behavior and reusability in automation tasks.
PowerShell functions bring structure and flexibility to your scripts, making them scalable, reusable, and easier to debug.
You can see the PowerShell function in action in this real-world script: Adding Microsoft 365 User to Multiple Groups that makes use of Add-UserToGroup function which takes in userId and a bunch of groupIds (as its function parameters) and adds the user to the provided groups.
Did You Know? Managing Microsoft 365 applications is even easier with automation. Try our Graph PowerShell scripts to automate tasks like generating reports, cleaning up inactive Teams, or assigning licenses efficiently.
Ready to get the most out of Microsoft 365 tools? Explore our free Microsoft 365 administration tools to simplify your administrative tasks and boost productivity.
© Your Site Name. All Rights Reserved. Design by HTML Codex