PowerShell Scripts

Production-ready PowerShell scripts for automation, security auditing, and system administration. Copy, download, and customize for your needs.

Get Entra ID User Report

Generate comprehensive user report from Entra ID with licenses and sign-in activity

Beginner
Entra ID ManagementScript #1
get-entra-user-report.ps1powershell
1class=class="text-pastel-mint">"text-foreground/50 italic"># Get comprehensive Entra ID user report
2Connect-MgGraph -Scopes class="text-pastel-mint">"User.Read.All", class="text-pastel-mint">"AuditLog.Read.All"
3
4$Users = Get-MgUser -All -Property DisplayName, UserPrincipalName, AccountEnabled, CreatedDateTime, SignInActivity, AssignedLicenses |
5 Select-Object DisplayName, UserPrincipalName, AccountEnabled, CreatedDateTime,
6 @{Name=class="text-pastel-mint">'LastSignIn';Expression={$_.SignInActivity.LastSignInDateTime}},
7 @{Name=class="text-pastel-mint">'LicenseCount';Expression={$_.AssignedLicenses.Count}}
8
9$Users | Export-Csv -Path class="text-pastel-mint">"EntraID_UserReport_$(Get-Date -Format 'yyyyMMddclass="text-pastel-mint">').csv" -NoTypeInformation
10Write-Host class="text-pastel-mint">"Report exported successfully!" -ForegroundColor Green
11$Users | Format-Table -AutoSize
Click the buttons above to copy or download

Create Bulk Entra ID Users from CSV

Automate user creation in Entra ID from CSV file with password generation

Intermediate
Entra ID ManagementScript #2
create-bulk-users.ps1powershell
1class=class="text-pastel-mint">"text-foreground/50 italic"># Create bulk users from CSV
2Connect-MgGraph -Scopes class="text-pastel-mint">"User.ReadWrite.All"
3
4class=class="text-pastel-mint">"text-foreground/50 italic"># CSV should have columns: DisplayName, UserPrincipalName, Department, JobTitle
5$Users = Import-Csv -Path class="text-pastel-mint">"C:\Users\NewUsers.csv"
6
7foreach ($User in $Users) {
8 $PasswordProfile = @{
9 Password = class="text-pastel-mint">"TempPass@" + (Get-Random -Minimum 1000 -Maximum 9999)
10 ForceChangePasswordNextSignIn = $true
11 }
12
13 $Params = @{
14 DisplayName = $User.DisplayName
15 UserPrincipalName = $User.UserPrincipalName
16 MailNickname = $User.UserPrincipalName.Split(class="text-pastel-mint">'@')[0]
17 AccountEnabled = $true
18 PasswordProfile = $PasswordProfile
19 Department = $User.Department
20 JobTitle = $User.JobTitle
21 }
22
23 try {
24 New-MgUser @Params
25 Write-Host class="text-pastel-mint">"Created: $($User.DisplayName)" -ForegroundColor Green
26 } catch {
27 Write-Host class="text-pastel-mint">"Failed: $($User.DisplayName) - $($_.Exception.Message)" -ForegroundColor Red
28 }
29}
Click the buttons above to copy or download

Audit Entra ID Admin Roles

List all users with administrative roles and their assignments

Intermediate
SecurityScript #3
audit-admin-roles.ps1powershell
1class=class="text-pastel-mint">"text-foreground/50 italic"># Audit administrative role assignments
2Connect-MgGraph -Scopes class="text-pastel-mint">"Directory.Read.All", class="text-pastel-mint">"RoleManagement.Read.All"
3
4$AdminRoles = Get-MgDirectoryRole | Where-Object { $_.DisplayName -like class="text-pastel-mint">"*Admin*" }
5$Report = @()
6
7foreach ($Role in $AdminRoles) {
8 $Members = Get-MgDirectoryRoleMember -DirectoryRoleId $Role.Id
9
10 foreach ($Member in $Members) {
11 $User = Get-MgUser -UserId $Member.Id
12 $Report += [PSCustomObject]@{
13 RoleName = $Role.DisplayName
14 UserName = $User.DisplayName
15 UPN = $User.UserPrincipalName
16 AccountEnabled = $User.AccountEnabled
17 }
18 }
19}
20
21$Report | Export-Csv -Path class="text-pastel-mint">"AdminRoles_$(Get-Date -Format 'yyyyMMddclass="text-pastel-mint">').csv" -NoTypeInformation
22Write-Host class="text-pastel-mint">"Found $($Report.Count) admin role assignments" -ForegroundColor Cyan
23$Report | Format-Table -AutoSize
Click the buttons above to copy or download

Enable MFA for Bulk Users

Enable multi-factor authentication for specified users or groups

Advanced
SecurityScript #4
enable-mfa-bulk.ps1powershell
1class=class="text-pastel-mint">"text-foreground/50 italic"># Enable MFA for bulk users
2Connect-MgGraph -Scopes class="text-pastel-mint">"UserAuthenticationMethod.ReadWrite.All"
3
4$Users = Get-MgUser -Filter class="text-pastel-mint">"department eq 'Financeclass="text-pastel-mint">'" -All
5
6foreach ($User in $Users) {
7 try {
8 class=class="text-pastel-mint">"text-foreground/50 italic"># Check current MFA status
9 $AuthMethods = Get-MgUserAuthenticationMethod -UserId $User.Id
10
11 class=class="text-pastel-mint">"text-foreground/50 italic"># Enable Phone Auth Method
12 $Params = @{
13 class="text-pastel-mint">"@odata.type" = class="text-pastel-mint">"class="text-foreground/50 italicclass="text-pastel-mint">">#microsoft.graph.phoneAuthenticationMethod"
14 phoneType = class="text-pastel-mint">"mobile"
15 phoneNumber = class="text-pastel-mint">"+1 555 0100" class=class="text-pastel-mint">"text-foreground/50 italic"># Update with actual number
16 }
17
18 New-MgUserAuthenticationPhoneMethod -UserId $User.Id -BodyParameter $Params
19 Write-Host class="text-pastel-mint">"MFA enabled for: $($User.DisplayName)" -ForegroundColor Green
20
21 } catch {
22 Write-Host class="text-pastel-mint">"Failed for: $($User.DisplayName) - $($_.Exception.Message)" -ForegroundColor Yellow
23 }
24}
25
26Write-Host class="text-pastel-mint">"MFA enablement completed" -ForegroundColor Cyan
Click the buttons above to copy or download

Find Inactive Entra ID Users

Identify users who haven't signed in for specified days

Beginner
Entra ID ManagementScript #5
get-inactive-users.ps1powershell
1class=class="text-pastel-mint">"text-foreground/50 italic"># Find inactive users in Entra ID
2Connect-MgGraph -Scopes class="text-pastel-mint">"User.Read.All", class="text-pastel-mint">"AuditLog.Read.All"
3
4$DaysInactive = 90
5$InactiveDate = (Get-Date).AddDays(-$DaysInactive)
6
7$InactiveUsers = Get-MgUser -All -Property DisplayName, UserPrincipalName, SignInActivity, CreatedDateTime |
8 Where-Object {
9 $_.SignInActivity.LastSignInDateTime -lt $InactiveDate -and
10 $_.SignInActivity.LastSignInDateTime -ne $null
11 } |
12 Select-Object DisplayName, UserPrincipalName,
13 @{Name=class="text-pastel-mint">'LastSignIn';Expression={$_.SignInActivity.LastSignInDateTime}},
14 @{Name=class="text-pastel-mint">'DaysInactive';Expression={((Get-Date) - $_.SignInActivity.LastSignInDateTime).Days}}
15
16Write-Host class="text-pastel-mint">"Found $($InactiveUsers.Count) inactive users (>$DaysInactive days)" -ForegroundColor Yellow
17$InactiveUsers | Export-Csv -Path class="text-pastel-mint">"InactiveUsers_$(Get-Date -Format 'yyyyMMddclass="text-pastel-mint">').csv" -NoTypeInformation
18$InactiveUsers | Format-Table -AutoSize
Click the buttons above to copy or download

Assign Licenses to Bulk Users

Assign Microsoft 365 licenses to users based on group or department

Intermediate
Entra ID ManagementScript #6
assign-licenses-bulk.ps1powershell
1class=class="text-pastel-mint">"text-foreground/50 italic"># Assign licenses to bulk users
2Connect-MgGraph -Scopes class="text-pastel-mint">"User.ReadWrite.All", class="text-pastel-mint">"Organization.Read.All"
3
4class=class="text-pastel-mint">"text-foreground/50 italic"># Get available SKUs
5$SKUs = Get-MgSubscribedSku
6$M365E3 = $SKUs | Where-Object { $_.SkuPartNumber -eq class="text-pastel-mint">"SPE_E3" }
7
8class=class="text-pastel-mint">"text-foreground/50 italic"># Get users from specific department
9$Users = Get-MgUser -Filter class="text-pastel-mint">"department eq 'Salesclass="text-pastel-mint">'" -All
10
11foreach ($User in $Users) {
12 try {
13 Set-MgUserLicense -UserId $User.Id -AddLicenses @{SkuId = $M365E3.SkuId} -RemoveLicenses @()
14 Write-Host class="text-pastel-mint">"License assigned to: $($User.DisplayName)" -ForegroundColor Green
15 } catch {
16 Write-Host class="text-pastel-mint">"Failed for: $($User.DisplayName) - $($_.Exception.Message)" -ForegroundColor Red
17 }
18}
19
20Write-Host class="text-pastel-mint">"License assignment completed" -ForegroundColor Cyan
Click the buttons above to copy or download

Create Entra ID Security Group

Create a new security group and add members dynamically

Beginner
IAMScript #7
create-security-group.ps1powershell
1class=class="text-pastel-mint">"text-foreground/50 italic"># Create Entra ID security group
2Connect-MgGraph -Scopes class="text-pastel-mint">"Group.ReadWrite.All"
3
4$GroupParams = @{
5 DisplayName = class="text-pastel-mint">"Security-Finance-Team"
6 Description = class="text-pastel-mint">"Finance department security group"
7 MailEnabled = $false
8 MailNickname = class="text-pastel-mint">"SecFinance"
9 SecurityEnabled = $true
10}
11
12$NewGroup = New-MgGroup @GroupParams
13Write-Host class="text-pastel-mint">"Group created: $($NewGroup.DisplayName)" -ForegroundColor Green
14
15class=class="text-pastel-mint">"text-foreground/50 italic"># Add members
16$Users = Get-MgUser -Filter class="text-pastel-mint">"department eq 'Financeclass="text-pastel-mint">'"
17foreach ($User in $Users) {
18 New-MgGroupMember -GroupId $NewGroup.Id -DirectoryObjectId $User.Id
19 Write-Host class="text-pastel-mint">"Added: $($User.DisplayName)" -ForegroundColor Cyan
20}
21
22Write-Host class="text-pastel-mint">"Group setup completed" -ForegroundColor Green
Click the buttons above to copy or download

Audit External Guest Users

Review all guest users and their access permissions

Intermediate
SecurityScript #8
audit-guest-users.ps1powershell
1class=class="text-pastel-mint">"text-foreground/50 italic"># Audit guest users in Entra ID
2Connect-MgGraph -Scopes class="text-pastel-mint">"User.Read.All", class="text-pastel-mint">"Group.Read.All"
3
4$GuestUsers = Get-MgUser -Filter class="text-pastel-mint">"userType eq 'Guestclass="text-pastel-mint">'" -All -Property DisplayName, UserPrincipalName, CreatedDateTime, SignInActivity
5
6$GuestReport = foreach ($Guest in $GuestUsers) {
7 $Groups = Get-MgUserMemberOf -UserId $Guest.Id
8
9 [PSCustomObject]@{
10 DisplayName = $Guest.DisplayName
11 Email = $Guest.UserPrincipalName
12 CreatedDate = $Guest.CreatedDateTime
13 LastSignIn = $Guest.SignInActivity.LastSignInDateTime
14 GroupCount = $Groups.Count
15 Groups = ($Groups.AdditionalProperties.displayName -join class="text-pastel-mint">"; ")
16 }
17}
18
19Write-Host class="text-pastel-mint">"Found $($GuestUsers.Count) guest users" -ForegroundColor Yellow
20$GuestReport | Export-Csv -Path class="text-pastel-mint">"GuestUsers_$(Get-Date -Format 'yyyyMMddclass="text-pastel-mint">').csv" -NoTypeInformation
21$GuestReport | Format-Table -AutoSize
Click the buttons above to copy or download

Export Conditional Access Policies

Document all Conditional Access policies and their settings

Advanced
SecurityScript #9
conditional-access-report.ps1powershell
1class=class="text-pastel-mint">"text-foreground/50 italic"># Export Conditional Access policies
2Connect-MgGraph -Scopes class="text-pastel-mint">"Policy.Read.All"
3
4$Policies = Get-MgIdentityConditionalAccessPolicy
5
6$Report = foreach ($Policy in $Policies) {
7 [PSCustomObject]@{
8 DisplayName = $Policy.DisplayName
9 State = $Policy.State
10 CreatedDateTime = $Policy.CreatedDateTime
11 ModifiedDateTime = $Policy.ModifiedDateTime
12 IncludeUsers = ($Policy.Conditions.Users.IncludeUsers -join class="text-pastel-mint">", ")
13 ExcludeUsers = ($Policy.Conditions.Users.ExcludeUsers -join class="text-pastel-mint">", ")
14 IncludeApplications = ($Policy.Conditions.Applications.IncludeApplications -join class="text-pastel-mint">", ")
15 GrantControls = ($Policy.GrantControls.BuiltInControls -join class="text-pastel-mint">", ")
16 SessionControls = if($Policy.SessionControls){class="text-pastel-mint">"Enabled"}else{class="text-pastel-mint">"None"}
17 }
18}
19
20$Report | Export-Csv -Path class="text-pastel-mint">"ConditionalAccess_$(Get-Date -Format 'yyyyMMddclass="text-pastel-mint">').csv" -NoTypeInformation
21Write-Host class="text-pastel-mint">"Exported $($Policies.Count) policies" -ForegroundColor Green
22$Report | Format-Table -AutoSize
Click the buttons above to copy or download

Revoke User Sessions and Tokens

Immediately revoke all sessions and refresh tokens for a compromised account

Intermediate
SecurityScript #10
revoke-user-sessions.ps1powershell
1class=class="text-pastel-mint">"text-foreground/50 italic"># Revoke all user sessions and tokens
2Connect-MgGraph -Scopes class="text-pastel-mint">"User.ReadWrite.All", class="text-pastel-mint">"Directory.ReadWrite.All"
3
4param(
5 [Parameter(Mandatory=$true)]
6 [string]$UserPrincipalName
7)
8
9$User = Get-MgUser -Filter class="text-pastel-mint">"userPrincipalName eq '$UserPrincipalNameclass="text-pastel-mint">'"
10
11if ($User) {
12 class=class="text-pastel-mint">"text-foreground/50 italic"># Revoke all refresh tokens
13 Revoke-MgUserSignInSession -UserId $User.Id
14
15 class=class="text-pastel-mint">"text-foreground/50 italic"># Disable account temporarily
16 Update-MgUser -UserId $User.Id -AccountEnabled $false
17
18 Write-Host class="text-pastel-mint">"User sessions revoked: $($User.DisplayName)" -ForegroundColor Yellow
19 Write-Host class="text-pastel-mint">"Account disabled for security" -ForegroundColor Yellow
20 Write-Host class="text-pastel-mint">"User ID: $($User.Id)" -ForegroundColor Cyan
21} else {
22 Write-Host class="text-pastel-mint">"User not found" -ForegroundColor Red
23}
Click the buttons above to copy or download

Get Microsoft 365 License Usage

Report on license allocation and available seats across all SKUs

Beginner
Entra ID ManagementScript #11
get-license-usage.ps1powershell
1class=class="text-pastel-mint">"text-foreground/50 italic"># Get license usage report
2Connect-MgGraph -Scopes class="text-pastel-mint">"Organization.Read.All"
3
4$SKUs = Get-MgSubscribedSku
5
6$LicenseReport = foreach ($SKU in $SKUs) {
7 [PSCustomObject]@{
8 ProductName = $SKU.SkuPartNumber
9 TotalLicenses = $SKU.PrepaidUnits.Enabled
10 AssignedLicenses = $SKU.ConsumedUnits
11 AvailableLicenses = $SKU.PrepaidUnits.Enabled - $SKU.ConsumedUnits
12 UtilizationPercent = [math]::Round(($SKU.ConsumedUnits / $SKU.PrepaidUnits.Enabled) * 100, 2)
13 }
14}
15
16Write-Host class="text-pastel-mint">"License Usage Summary" -ForegroundColor Cyan
17$LicenseReport | Format-Table -AutoSize
18$LicenseReport | Export-Csv -Path class="text-pastel-mint">"LicenseUsage_$(Get-Date -Format 'yyyyMMddclass="text-pastel-mint">').csv" -NoTypeInformation
Click the buttons above to copy or download

Sync Group Membership by Attribute

Automatically sync group membership based on user attributes

Advanced
IAMScript #12
sync-group-membership.ps1powershell
1class=class="text-pastel-mint">"text-foreground/50 italic"># Sync group membership based on department
2Connect-MgGraph -Scopes class="text-pastel-mint">"Group.ReadWrite.All", class="text-pastel-mint">"User.Read.All"
3
4param(
5 [string]$Department = class="text-pastel-mint">"Engineering",
6 [string]$GroupName = class="text-pastel-mint">"Engineering-Team"
7)
8
9$Group = Get-MgGroup -Filter class="text-pastel-mint">"displayName eq '$GroupNameclass="text-pastel-mint">'"
10$UsersInDept = Get-MgUser -Filter class="text-pastel-mint">"department eq '$Departmentclass="text-pastel-mint">'" -All
11$CurrentMembers = Get-MgGroupMember -GroupId $Group.Id -All
12
13class=class="text-pastel-mint">"text-foreground/50 italic"># Add missing users
14foreach ($User in $UsersInDept) {
15 if ($User.Id -notin $CurrentMembers.Id) {
16 New-MgGroupMember -GroupId $Group.Id -DirectoryObjectId $User.Id
17 Write-Host class="text-pastel-mint">"Added: $($User.DisplayName)" -ForegroundColor Green
18 }
19}
20
21class=class="text-pastel-mint">"text-foreground/50 italic"># Remove users no longer in department
22foreach ($Member in $CurrentMembers) {
23 if ($Member.Id -notin $UsersInDept.Id) {
24 Remove-MgGroupMemberByRef -GroupId $Group.Id -DirectoryObjectId $Member.Id
25 Write-Host class="text-pastel-mint">"Removed: $($Member.AdditionalProperties.displayName)" -ForegroundColor Yellow
26 }
27}
28
29Write-Host class="text-pastel-mint">"Group sync completed" -ForegroundColor Cyan
Click the buttons above to copy or download

Reset User Password Securely

Reset user password with strong password generation and notification

Beginner
Entra ID ManagementScript #13
reset-user-password.ps1powershell
1class=class="text-pastel-mint">"text-foreground/50 italic"># Reset user password securely
2Connect-MgGraph -Scopes class="text-pastel-mint">"User.ReadWrite.All"
3
4function Reset-EntraUserPassword {
5 param(
6 [Parameter(Mandatory=$true)]
7 [string]$UserPrincipalName,
8 [switch]$ForceChange
9 )
10
11 class=class="text-pastel-mint">"text-foreground/50 italic"># Generate strong password
12 $Password = -join ((65..90) + (97..122) + (48..57) + (33,35,37,64) | Get-Random -Count 16 | ForEach-Object {[char]$_})
13
14 $PasswordProfile = @{
15 Password = $Password
16 ForceChangePasswordNextSignIn = $ForceChange.IsPresent
17 }
18
19 try {
20 $User = Get-MgUser -Filter class="text-pastel-mint">"userPrincipalName eq '$UserPrincipalNameclass="text-pastel-mint">'"
21 Update-MgUser -UserId $User.Id -PasswordProfile $PasswordProfile
22
23 Write-Host class="text-pastel-mint">"Password reset successful for: $($User.DisplayName)" -ForegroundColor Green
24 Write-Host class="text-pastel-mint">"Temporary Password: $Password" -ForegroundColor Yellow
25 Write-Host class="text-pastel-mint">"Force Change: $($ForceChange.IsPresent)" -ForegroundColor Cyan
26
27 } catch {
28 Write-Host class="text-pastel-mint">"Error: $($_.Exception.Message)" -ForegroundColor Red
29 }
30}
31
32class=class="text-pastel-mint">"text-foreground/50 italic"># Usage
33Reset-EntraUserPassword -UserPrincipalName class="text-pastel-mint">"user@domain.com" -ForceChange
Click the buttons above to copy or download

Export All Group Memberships

Export all groups and their members to CSV for documentation

Intermediate
Entra ID ManagementScript #14
export-group-members.ps1powershell
1class=class="text-pastel-mint">"text-foreground/50 italic"># Export all group memberships
2Connect-MgGraph -Scopes class="text-pastel-mint">"Group.Read.All", class="text-pastel-mint">"User.Read.All"
3
4$AllGroups = Get-MgGroup -All
5$Report = @()
6
7foreach ($Group in $AllGroups) {
8 Write-Host class="text-pastel-mint">"Processing: $($Group.DisplayName)" -ForegroundColor Cyan
9
10 $Members = Get-MgGroupMember -GroupId $Group.Id -All
11
12 foreach ($Member in $Members) {
13 $Report += [PSCustomObject]@{
14 GroupName = $Group.DisplayName
15 GroupType = if($Group.SecurityEnabled){class="text-pastel-mint">"Security"}else{class="text-pastel-mint">"Microsoft 365"}
16 MemberName = $Member.AdditionalProperties.displayName
17 MemberUPN = $Member.AdditionalProperties.userPrincipalName
18 MemberType = $Member.AdditionalProperties.class="text-pastel-mint">'@odata.type'
19 }
20 }
21}
22
23Write-Host class="text-pastel-mint">"Total memberships: $($Report.Count)" -ForegroundColor Green
24$Report | Export-Csv -Path class="text-pastel-mint">"GroupMemberships_$(Get-Date -Format 'yyyyMMddclass="text-pastel-mint">').csv" -NoTypeInformation
Click the buttons above to copy or download

Audit Application Permissions

Review all application registrations and their API permissions

Advanced
SecurityScript #15
audit-app-permissions.ps1powershell
1class=class="text-pastel-mint">"text-foreground/50 italic"># Audit application permissions
2Connect-MgGraph -Scopes class="text-pastel-mint">"Application.Read.All"
3
4$Apps = Get-MgApplication -All
5$Report = @()
6
7foreach ($App in $Apps) {
8 $Permissions = $App.RequiredResourceAccess
9
10 foreach ($Resource in $Permissions) {
11 foreach ($Permission in $Resource.ResourceAccess) {
12 $Report += [PSCustomObject]@{
13 ApplicationName = $App.DisplayName
14 ApplicationId = $App.AppId
15 ResourceId = $Resource.ResourceAppId
16 PermissionId = $Permission.Id
17 PermissionType = $Permission.Type
18 CreatedDateTime = $App.CreatedDateTime
19 }
20 }
21 }
22}
23
24Write-Host class="text-pastel-mint">"Found $($Apps.Count) applications with $($Report.Count) permissions" -ForegroundColor Cyan
25$Report | Export-Csv -Path class="text-pastel-mint">"AppPermissions_$(Get-Date -Format 'yyyyMMddclass="text-pastel-mint">').csv" -NoTypeInformation
26$Report | Format-Table ApplicationName, PermissionType -AutoSize
Click the buttons above to copy or download

Disable Inactive User Accounts

Automatically disable accounts that haven't been used for specified period

Intermediate
SecurityScript #16
disable-inactive-accounts.ps1powershell
1class=class="text-pastel-mint">"text-foreground/50 italic"># Disable inactive user accounts
2Connect-MgGraph -Scopes class="text-pastel-mint">"User.ReadWrite.All", class="text-pastel-mint">"AuditLog.Read.All"
3
4$DaysInactive = 90
5$InactiveDate = (Get-Date).AddDays(-$DaysInactive)
6
7$InactiveUsers = Get-MgUser -All -Property DisplayName, UserPrincipalName, AccountEnabled, SignInActivity |
8 Where-Object {
9 $_.AccountEnabled -eq $true -and
10 $_.SignInActivity.LastSignInDateTime -lt $InactiveDate
11 }
12
13Write-Host class="text-pastel-mint">"Found $($InactiveUsers.Count) inactive accounts to disable" -ForegroundColor Yellow
14
15foreach ($User in $InactiveUsers) {
16 try {
17 Update-MgUser -UserId $User.Id -AccountEnabled $false
18 Write-Host class="text-pastel-mint">"Disabled: $($User.DisplayName) - Last sign-in: $($User.SignInActivity.LastSignInDateTime)" -ForegroundColor Yellow
19 } catch {
20 Write-Host class="text-pastel-mint">"Failed to disable: $($User.DisplayName)" -ForegroundColor Red
21 }
22}
23
24Write-Host class="text-pastel-mint">"Account cleanup completed" -ForegroundColor Cyan
Click the buttons above to copy or download

Create Dynamic Entra ID Group

Create a dynamic group with membership rules based on user attributes

Advanced
IAMScript #17
create-dynamic-group.ps1powershell
1class=class="text-pastel-mint">"text-foreground/50 italic"># Create dynamic group with membership rules
2Connect-MgGraph -Scopes class="text-pastel-mint">"Group.ReadWrite.All"
3
4$DynamicRule = class="text-pastel-mint">'(user.department -eq "ITclass="text-pastel-mint">") and (user.accountEnabled -eq true)'
5
6$GroupParams = @{
7 DisplayName = class="text-pastel-mint">"IT-Department-Dynamic"
8 Description = class="text-pastel-mint">"Dynamic group for IT department members"
9 MailEnabled = $false
10 MailNickname = class="text-pastel-mint">"ITDeptDynamic"
11 SecurityEnabled = $true
12 GroupTypes = @(class="text-pastel-mint">"DynamicMembership")
13 MembershipRule = $DynamicRule
14 MembershipRuleProcessingState = class="text-pastel-mint">"On"
15}
16
17try {
18 $NewGroup = New-MgGroup @GroupParams
19 Write-Host class="text-pastel-mint">"Dynamic group created: $($NewGroup.DisplayName)" -ForegroundColor Green
20 Write-Host class="text-pastel-mint">"Membership Rule: $DynamicRule" -ForegroundColor Cyan
21 Write-Host class="text-pastel-mint">"Group ID: $($NewGroup.Id)" -ForegroundColor Cyan
22} catch {
23 Write-Host class="text-pastel-mint">"Error: $($_.Exception.Message)" -ForegroundColor Red
24}
Click the buttons above to copy or download

Audit Privileged Identity Management

Review PIM role assignments and eligible users

Advanced
SecurityScript #18
audit-privileged-users.ps1powershell
1class=class="text-pastel-mint">"text-foreground/50 italic"># Audit PIM role assignments
2Connect-MgGraph -Scopes class="text-pastel-mint">"RoleManagement.Read.All", class="text-pastel-mint">"PrivilegedAccess.Read.AzureAD"
3
4$RoleDefinitions = Get-MgRoleManagementDirectoryRoleDefinition -All
5$Report = @()
6
7foreach ($Role in $RoleDefinitions | Where-Object { $_.DisplayName -like class="text-pastel-mint">"*Admin*" }) {
8 class=class="text-pastel-mint">"text-foreground/50 italic"># Get active assignments
9 $Assignments = Get-MgRoleManagementDirectoryRoleAssignment -Filter class="text-pastel-mint">"roleDefinitionId eq '$($Role.Id)class="text-pastel-mint">'" -All
10
11 foreach ($Assignment in $Assignments) {
12 $Principal = Get-MgDirectoryObject -DirectoryObjectId $Assignment.PrincipalId
13
14 $Report += [PSCustomObject]@{
15 RoleName = $Role.DisplayName
16 PrincipalName = $Principal.AdditionalProperties.displayName
17 PrincipalType = $Principal.AdditionalProperties.class="text-pastel-mint">'@odata.type'
18 AssignmentType = class="text-pastel-mint">"Active"
19 StartDateTime = $Assignment.CreatedDateTime
20 }
21 }
22}
23
24Write-Host class="text-pastel-mint">"Found $($Report.Count) privileged role assignments" -ForegroundColor Yellow
25$Report | Export-Csv -Path class="text-pastel-mint">"PIMRoles_$(Get-Date -Format 'yyyyMMddclass="text-pastel-mint">').csv" -NoTypeInformation
26$Report | Format-Table -AutoSize
Click the buttons above to copy or download

Monitor Failed Sign-In Attempts

Track and report on failed sign-in attempts for security monitoring

Intermediate
SecurityScript #19
monitor-sign-in-failures.ps1powershell
1class=class="text-pastel-mint">"text-foreground/50 italic"># Monitor failed sign-in attempts
2Connect-MgGraph -Scopes class="text-pastel-mint">"AuditLog.Read.All", class="text-pastel-mint">"Directory.Read.All"
3
4$StartDate = (Get-Date).AddDays(-7)
5$SignIns = Get-MgAuditLogSignIn -Filter class="text-pastel-mint">"createdDateTime ge $($StartDate.ToString('yyyy-MM-ddclass="text-pastel-mint">')) and status/errorCode ne 0" -All
6
7$FailureReport = $SignIns | Group-Object UserPrincipalName | ForEach-Object {
8 [PSCustomObject]@{
9 UserPrincipalName = $_.Name
10 FailedAttempts = $_.Count
11 LastFailure = ($_.Group | Sort-Object CreatedDateTime -Descending | Select-Object -First 1).CreatedDateTime
12 ErrorCodes = ($_.Group.Status.ErrorCode | Select-Object -Unique) -join class="text-pastel-mint">", "
13 Locations = ($_.Group.Location.City | Select-Object -Unique) -join class="text-pastel-mint">", "
14 }
15} | Sort-Object FailedAttempts -Descending
16
17Write-Host class="text-pastel-mint">"Found $($FailureReport.Count) users with failed sign-ins" -ForegroundColor Yellow
18$FailureReport | Export-Csv -Path class="text-pastel-mint">"FailedSignIns_$(Get-Date -Format 'yyyyMMddclass="text-pastel-mint">').csv" -NoTypeInformation
19$FailureReport | Format-Table -AutoSize
Click the buttons above to copy or download

Manage Service Principal Secrets

Audit and rotate service principal client secrets for security

Advanced
SecurityScript #20
manage-service-principals.ps1powershell
1class=class="text-pastel-mint">"text-foreground/50 italic"># Manage service principal secrets
2Connect-MgGraph -Scopes class="text-pastel-mint">"Application.ReadWrite.All"
3
4$Apps = Get-MgApplication -All
5$ExpiringSecrets = @()
6$WarningDays = 30
7
8foreach ($App in $Apps) {
9 $Secrets = $App.PasswordCredentials
10
11 foreach ($Secret in $Secrets) {
12 $DaysUntilExpiry = ($Secret.EndDateTime - (Get-Date)).Days
13
14 if ($DaysUntilExpiry -le $WarningDays -and $DaysUntilExpiry -gt 0) {
15 $ExpiringSecrets += [PSCustomObject]@{
16 ApplicationName = $App.DisplayName
17 ApplicationId = $App.AppId
18 SecretKeyId = $Secret.KeyId
19 ExpiryDate = $Secret.EndDateTime
20 DaysRemaining = $DaysUntilExpiry
21 }
22 }
23 }
24}
25
26Write-Host class="text-pastel-mint">"Found $($ExpiringSecrets.Count) secrets expiring in $WarningDays days" -ForegroundColor Yellow
27$ExpiringSecrets | Sort-Object DaysRemaining | Export-Csv -Path class="text-pastel-mint">"ExpiringSecrets_$(Get-Date -Format 'yyyyMMddclass="text-pastel-mint">').csv" -NoTypeInformation
28$ExpiringSecrets | Format-Table -AutoSize
Click the buttons above to copy or download

Configure Domain Password Policy

Set and enforce password policy settings for the tenant

Intermediate
SecurityScript #21
configure-password-policy.ps1powershell
1class=class="text-pastel-mint">"text-foreground/50 italic"># Configure password policy settings
2Connect-MgGraph -Scopes class="text-pastel-mint">"Policy.ReadWrite.Authorization"
3
4class=class="text-pastel-mint">"text-foreground/50 italic"># Get current domain settings
5$Domain = Get-MgDomain | Where-Object { $_.IsDefault -eq $true }
6
7class=class="text-pastel-mint">"text-foreground/50 italic"># Configure password policy
8$PasswordPolicy = @{
9 passwordValidityPeriodInDays = 90
10 passwordNotificationWindowInDays = 14
11}
12
13try {
14 class=class="text-pastel-mint">"text-foreground/50 italic"># Note: Password policies are typically set at the tenant level
15 Write-Host class="text-pastel-mint">"Current Password Policy Settings:" -ForegroundColor Cyan
16 Write-Host class="text-pastel-mint">"Domain: $($Domain.Id)" -ForegroundColor White
17 Write-Host class="text-pastel-mint">"Password Never Expires: $($Domain.PasswordValidityPeriodInDays)" -ForegroundColor White
18
19 class=class="text-pastel-mint">"text-foreground/50 italic"># Additional password protection settings
20 Write-Host class="text-pastel-mint">"`nRecommended Settings:" -ForegroundColor Yellow
21 Write-Host class="text-pastel-mint">"- Enable Azure AD Password Protection" -ForegroundColor White
22 Write-Host class="text-pastel-mint">"- Set minimum password length to 14 characters" -ForegroundColor White
23 Write-Host class="text-pastel-mint">"- Enable banned password list" -ForegroundColor White
24 Write-Host class="text-pastel-mint">"- Require MFA for all users" -ForegroundColor White
25
26} catch {
27 Write-Host class="text-pastel-mint">"Error: $($_.Exception.Message)" -ForegroundColor Red
28}
Click the buttons above to copy or download

Export Entra ID Device Inventory

Generate comprehensive report of all registered devices

Beginner
Entra ID ManagementScript #22
export-device-inventory.ps1powershell
1class=class="text-pastel-mint">"text-foreground/50 italic"># Export device inventory from Entra ID
2Connect-MgGraph -Scopes class="text-pastel-mint">"Device.Read.All"
3
4$Devices = Get-MgDevice -All -Property DisplayName, DeviceId, OperatingSystem, OperatingSystemVersion, TrustType, ApproximateLastSignInDateTime, IsCompliant, IsManaged
5
6$DeviceReport = $Devices | Select-Object DisplayName, DeviceId, OperatingSystem, OperatingSystemVersion, TrustType,
7 @{Name=class="text-pastel-mint">'LastSignIn';Expression={$_.ApproximateLastSignInDateTime}},
8 @{Name=class="text-pastel-mint">'Compliant';Expression={$_.IsCompliant}},
9 @{Name=class="text-pastel-mint">'Managed';Expression={$_.IsManaged}},
10 @{Name=class="text-pastel-mint">'DaysSinceSignIn';Expression={if($_.ApproximateLastSignInDateTime){((Get-Date) - $_.ApproximateLastSignInDateTime).Days}else{class="text-pastel-mint">"Never"}}}
11
12Write-Host class="text-pastel-mint">"Total Devices: $($Devices.Count)" -ForegroundColor Cyan
13Write-Host class="text-pastel-mint">"Compliant: $(($Devices | Where-Object IsCompliant -eq $true).Count)" -ForegroundColor Green
14Write-Host class="text-pastel-mint">"Non-Compliant: $(($Devices | Where-Object IsCompliant -eq $false).Count)" -ForegroundColor Red
15
16$DeviceReport | Export-Csv -Path class="text-pastel-mint">"DeviceInventory_$(Get-Date -Format 'yyyyMMddclass="text-pastel-mint">').csv" -NoTypeInformation
17$DeviceReport | Format-Table -AutoSize
Click the buttons above to copy or download

Set User Manager Relationships

Bulk update manager assignments from CSV file

Intermediate
Entra ID ManagementScript #23
assign-manager-hierarchy.ps1powershell
1class=class="text-pastel-mint">"text-foreground/50 italic"># Set manager relationships in bulk
2Connect-MgGraph -Scopes class="text-pastel-mint">"User.ReadWrite.All"
3
4class=class="text-pastel-mint">"text-foreground/50 italic"># CSV should have columns: UserPrincipalName, ManagerPrincipalName
5$Assignments = Import-Csv -Path class="text-pastel-mint">"C:\Managers\ManagerAssignments.csv"
6
7foreach ($Assignment in $Assignments) {
8 try {
9 $User = Get-MgUser -Filter class="text-pastel-mint">"userPrincipalName eq '$($Assignment.UserPrincipalName)class="text-pastel-mint">'"
10 $Manager = Get-MgUser -Filter class="text-pastel-mint">"userPrincipalName eq '$($Assignment.ManagerPrincipalName)class="text-pastel-mint">'"
11
12 if ($User -and $Manager) {
13 $ManagerRef = @{
14 class="text-pastel-mint">"@odata.id" = class="text-pastel-mint">"https://graph.microsoft.com/v1.0/users/$($Manager.Id)"
15 }
16
17 Set-MgUserManagerByRef -UserId $User.Id -BodyParameter $ManagerRef
18 Write-Host class="text-pastel-mint">"Assigned manager for: $($User.DisplayName) -> $($Manager.DisplayName)" -ForegroundColor Green
19 }
20 } catch {
21 Write-Host class="text-pastel-mint">"Failed: $($Assignment.UserPrincipalName) - $($_.Exception.Message)" -ForegroundColor Red
22 }
23}
24
25Write-Host class="text-pastel-mint">"Manager assignment completed" -ForegroundColor Cyan
Click the buttons above to copy or download

Audit Risky User Accounts

Identify and report on users flagged for risk by Identity Protection

Advanced
SecurityScript #24
audit-risky-users.ps1powershell
1class=class="text-pastel-mint">"text-foreground/50 italic"># Audit risky users from Identity Protection
2Connect-MgGraph -Scopes class="text-pastel-mint">"IdentityRiskyUser.Read.All"
3
4$RiskyUsers = Get-MgRiskyUser -All
5
6$RiskReport = foreach ($User in $RiskyUsers | Where-Object { $_.RiskState -ne class="text-pastel-mint">'none' }) {
7 try {
8 $UserDetails = Get-MgUser -UserId $User.Id -Property DisplayName, UserPrincipalName, Department
9
10 [PSCustomObject]@{
11 DisplayName = $UserDetails.DisplayName
12 UserPrincipalName = $UserDetails.UserPrincipalName
13 Department = $UserDetails.Department
14 RiskLevel = $User.RiskLevel
15 RiskState = $User.RiskState
16 RiskLastUpdated = $User.RiskLastUpdatedDateTime
17 RiskDetail = $User.RiskDetail
18 }
19 } catch {
20 Write-Host class="text-pastel-mint">"Error processing user: $($User.UserPrincipalName)" -ForegroundColor Yellow
21 }
22}
23
24Write-Host class="text-pastel-mint">"Found $($RiskReport.Count) risky users" -ForegroundColor Yellow
25$RiskReport | Export-Csv -Path class="text-pastel-mint">"RiskyUsers_$(Get-Date -Format 'yyyyMMddclass="text-pastel-mint">').csv" -NoTypeInformation
26$RiskReport | Format-Table -AutoSize
Click the buttons above to copy or download

Remove Stale Entra ID Devices

Identify and remove devices that haven't signed in for specified days

Intermediate
Entra ID ManagementScript #25
remove-stale-devices.ps1powershell
1class=class="text-pastel-mint">"text-foreground/50 italic"># Remove stale devices from Entra ID
2Connect-MgGraph -Scopes class="text-pastel-mint">"Device.ReadWrite.All"
3
4$DaysInactive = 90
5$InactiveDate = (Get-Date).AddDays(-$DaysInactive)
6
7$StaleDevices = Get-MgDevice -All | Where-Object {
8 $_.ApproximateLastSignInDateTime -lt $InactiveDate -and
9 $_.ApproximateLastSignInDateTime -ne $null
10}
11
12Write-Host class="text-pastel-mint">"Found $($StaleDevices.Count) stale devices (>$DaysInactive days inactive)" -ForegroundColor Yellow
13
14foreach ($Device in $StaleDevices) {
15 $DaysInactive = ((Get-Date) - $Device.ApproximateLastSignInDateTime).Days
16
17 Write-Host class="text-pastel-mint">"Device: $($Device.DisplayName) - Last Sign-In: $($Device.ApproximateLastSignInDateTime) ($DaysInactive days)" -ForegroundColor Cyan
18
19 class=class="text-pastel-mint">"text-foreground/50 italic"># Uncomment to actually delete devices
20 class=class="text-pastel-mint">"text-foreground/50 italic"># Remove-MgDevice -DeviceId $Device.Id
21 class=class="text-pastel-mint">"text-foreground/50 italic"># Write-Host class="text-pastel-mint">"Removed: $($Device.DisplayName)" -ForegroundColor Red
22}
23
24Write-Host class="text-pastel-mint">"`nReview complete. Uncomment removal code to delete devices." -ForegroundColor Yellow
Click the buttons above to copy or download

Create Application Registration

Register new application with API permissions and secrets

Advanced
IAMScript #26
create-app-registration.ps1powershell
1class=class="text-pastel-mint">"text-foreground/50 italic"># Create new application registration
2Connect-MgGraph -Scopes class="text-pastel-mint">"Application.ReadWrite.All"
3
4$AppName = class="text-pastel-mint">"MyCustomApplication"
5
6class=class="text-pastel-mint">"text-foreground/50 italic"># Define required API permissions
7$RequiredResourceAccess = @{
8 ResourceAppId = class="text-pastel-mint">"00000003-0000-0000-c000-000000000000" class=class="text-pastel-mint">"text-foreground/50 italic"># Microsoft Graph
9 ResourceAccess = @(
10 @{
11 Id = class="text-pastel-mint">"e1fe6dd8-ba31-4d61-89e7-88639da4683d" class=class="text-pastel-mint">"text-foreground/50 italic"># User.Read
12 Type = class="text-pastel-mint">"Scope"
13 },
14 @{
15 Id = class="text-pastel-mint">"df021288-bdef-4463-88db-98f22de89214" class=class="text-pastel-mint">"text-foreground/50 italic"># User.Read.All
16 Type = class="text-pastel-mint">"Role"
17 }
18 )
19}
20
21$AppParams = @{
22 DisplayName = $AppName
23 SignInAudience = class="text-pastel-mint">"AzureADMyOrg"
24 RequiredResourceAccess = @($RequiredResourceAccess)
25}
26
27try {
28 $App = New-MgApplication @AppParams
29 Write-Host class="text-pastel-mint">"Application created: $($App.DisplayName)" -ForegroundColor Green
30 Write-Host class="text-pastel-mint">"Application ID: $($App.AppId)" -ForegroundColor Cyan
31 Write-Host class="text-pastel-mint">"Object ID: $($App.Id)" -ForegroundColor Cyan
32
33 class=class="text-pastel-mint">"text-foreground/50 italic"># Create client secret
34 $SecretParams = @{
35 PasswordCredential = @{
36 DisplayName = class="text-pastel-mint">"Auto-generated secret"
37 }
38 }
39 $Secret = Add-MgApplicationPassword -ApplicationId $App.Id -BodyParameter $SecretParams
40 Write-Host class="text-pastel-mint">"Client Secret: $($Secret.SecretText)" -ForegroundColor Yellow
41 Write-Host class="text-pastel-mint">"Secret Expiry: $($Secret.EndDateTime)" -ForegroundColor Yellow
42
43} catch {
44 Write-Host class="text-pastel-mint">"Error: $($_.Exception.Message)" -ForegroundColor Red
45}
Click the buttons above to copy or download

Export Sign-In Logs with Analytics

Export and analyze sign-in logs for security and compliance reporting

Intermediate
ComplianceScript #27
export-signin-logs.ps1powershell
1class=class="text-pastel-mint">"text-foreground/50 italic"># Export and analyze sign-in logs
2Connect-MgGraph -Scopes class="text-pastel-mint">"AuditLog.Read.All", class="text-pastel-mint">"Directory.Read.All"
3
4$StartDate = (Get-Date).AddDays(-30)
5$SignIns = Get-MgAuditLogSignIn -Filter class="text-pastel-mint">"createdDateTime ge $($StartDate.ToString('yyyy-MM-ddclass="text-pastel-mint">'))" -All
6
7Write-Host class="text-pastel-mint">"Processing $($SignIns.Count) sign-in events..." -ForegroundColor Cyan
8
9$SignInReport = $SignIns | Select-Object @{Name=class="text-pastel-mint">'User';Expression={$_.UserPrincipalName}},
10 @{Name=class="text-pastel-mint">'DateTime';Expression={$_.CreatedDateTime}},
11 @{Name=class="text-pastel-mint">'Status';Expression={if($_.Status.ErrorCode -eq 0){class="text-pastel-mint">"Success"}else{class="text-pastel-mint">"Failed"}}},
12 @{Name=class="text-pastel-mint">'ErrorCode';Expression={$_.Status.ErrorCode}},
13 @{Name=class="text-pastel-mint">'Application';Expression={$_.AppDisplayName}},
14 @{Name=class="text-pastel-mint">'IPAddress';Expression={$_.IPAddress}},
15 @{Name=class="text-pastel-mint">'City';Expression={$_.Location.City}},
16 @{Name=class="text-pastel-mint">'Country';Expression={$_.Location.CountryOrRegion}},
17 @{Name=class="text-pastel-mint">'DeviceOS';Expression={$_.DeviceDetail.OperatingSystem}}
18
19class=class="text-pastel-mint">"text-foreground/50 italic"># Generate statistics
20$TotalSignIns = $SignInReport.Count
21$SuccessfulSignIns = ($SignInReport | Where-Object Status -eq class="text-pastel-mint">"Success").Count
22$FailedSignIns = ($SignInReport | Where-Object Status -eq class="text-pastel-mint">"Failed").Count
23
24Write-Host class="text-pastel-mint">"`nSign-In Statistics:" -ForegroundColor Green
25Write-Host class="text-pastel-mint">"Total: $TotalSignIns" -ForegroundColor White
26Write-Host class="text-pastel-mint">"Successful: $SuccessfulSignIns" -ForegroundColor Green
27Write-Host class="text-pastel-mint">"Failed: $FailedSignIns" -ForegroundColor Red
28
29$SignInReport | Export-Csv -Path class="text-pastel-mint">"SignInLogs_$(Get-Date -Format 'yyyyMMddclass="text-pastel-mint">').csv" -NoTypeInformation
Click the buttons above to copy or download

Configure Guest User Access Settings

Manage external collaboration settings and guest user permissions

Advanced
IAMScript #28
manage-guest-access.ps1powershell
1class=class="text-pastel-mint">"text-foreground/50 italic"># Configure guest user access settings
2Connect-MgGraph -Scopes class="text-pastel-mint">"Policy.ReadWrite.Authorization"
3
4class=class="text-pastel-mint">"text-foreground/50 italic"># Get current authorization policy
5$AuthPolicy = Get-MgPolicyAuthorizationPolicy
6
7Write-Host class="text-pastel-mint">"Current Guest User Access Settings:" -ForegroundColor Cyan
8Write-Host class="text-pastel-mint">"Allow Invitations From: $($AuthPolicy.AllowInvitesFrom)" -ForegroundColor White
9Write-Host class="text-pastel-mint">"Guest User Role: $($AuthPolicy.GuestUserRoleId)" -ForegroundColor White
10
11class=class="text-pastel-mint">"text-foreground/50 italic"># Update guest user settings (example)
12$UpdateParams = @{
13 AllowInvitesFrom = class="text-pastel-mint">"adminsAndGuestInviters" class=class="text-pastel-mint">"text-foreground/50 italic"># Options: none, adminsAndGuestInviters, adminsGuestInvitersAndAllMembers, everyone
14 AllowedToSignUpEmailBasedSubscriptions = $false
15 AllowedToUseSspr = $false
16 AllowEmailVerifiedUsersToJoinOrganization = $false
17 BlockMsolPowerShell = $true
18}
19
20try {
21 Update-MgPolicyAuthorizationPolicy -AuthorizationPolicyId $AuthPolicy.Id -BodyParameter $UpdateParams
22 Write-Host class="text-pastel-mint">"`nGuest access settings updated successfully" -ForegroundColor Green
23} catch {
24 Write-Host class="text-pastel-mint">"Error: $($_.Exception.Message)" -ForegroundColor Red
25}
26
27class=class="text-pastel-mint">"text-foreground/50 italic"># List current guest users
28$Guests = Get-MgUser -Filter class="text-pastel-mint">"userType eq 'Guestclass="text-pastel-mint">'" -All
29Write-Host class="text-pastel-mint">"`nTotal Guest Users: $($Guests.Count)" -ForegroundColor Yellow
Click the buttons above to copy or download

Audit MFA Registration Status

Check MFA registration status for all users and identify gaps

Intermediate
SecurityScript #29
audit-mfa-status.ps1powershell
1class=class="text-pastel-mint">"text-foreground/50 italic"># Audit MFA registration status
2Connect-MgGraph -Scopes class="text-pastel-mint">"UserAuthenticationMethod.Read.All", class="text-pastel-mint">"User.Read.All"
3
4$Users = Get-MgUser -All -Property DisplayName, UserPrincipalName, AccountEnabled
5$MFAReport = @()
6
7foreach ($User in $Users | Where-Object AccountEnabled -eq $true) {
8 try {
9 $AuthMethods = Get-MgUserAuthenticationMethod -UserId $User.Id
10
11 $HasMFA = $AuthMethods.AdditionalProperties.class="text-pastel-mint">'@odata.type' -contains class="text-pastel-mint">'class="text-foreground/50 italicclass="text-pastel-mint">">#microsoft.graph.phoneAuthenticationMethod' -or
12 $AuthMethods.AdditionalProperties.class="text-pastel-mint">'@odata.type' -contains class="text-pastel-mint">'class="text-foreground/50 italicclass="text-pastel-mint">">#microsoft.graph.microsoftAuthenticatorAuthenticationMethod'
13
14 $MFAReport += [PSCustomObject]@{
15 DisplayName = $User.DisplayName
16 UserPrincipalName = $User.UserPrincipalName
17 MFAEnabled = $HasMFA
18 AuthMethodCount = $AuthMethods.Count
19 Methods = ($AuthMethods.AdditionalProperties.class="text-pastel-mint">'@odata.type' -replace class="text-pastel-mint">'class="text-foreground/50 italicclass="text-pastel-mint">">#microsoft.graph.', class="text-pastel-mint">'') -join class="text-pastel-mint">", "
20 }
21 } catch {
22 Write-Host class="text-pastel-mint">"Error processing: $($User.UserPrincipalName)" -ForegroundColor Yellow
23 }
24}
25
26$MFAEnabled = ($MFAReport | Where-Object MFAEnabled -eq $true).Count
27$MFADisabled = ($MFAReport | Where-Object MFAEnabled -eq $false).Count
28
29Write-Host class="text-pastel-mint">"MFA Status Summary:" -ForegroundColor Cyan
30Write-Host class="text-pastel-mint">"Enabled: $MFAEnabled" -ForegroundColor Green
31Write-Host class="text-pastel-mint">"Not Enabled: $MFADisabled" -ForegroundColor Red
32
33$MFAReport | Export-Csv -Path class="text-pastel-mint">"MFAStatus_$(Get-Date -Format 'yyyyMMddclass="text-pastel-mint">').csv" -NoTypeInformation
Click the buttons above to copy or download

Sync User Attributes from CSV

Bulk update user properties like department, title, and location

Intermediate
Entra ID ManagementScript #30
sync-user-attributes.ps1powershell
1class=class="text-pastel-mint">"text-foreground/50 italic"># Bulk update user attributes from CSV
2Connect-MgGraph -Scopes class="text-pastel-mint">"User.ReadWrite.All"
3
4class=class="text-pastel-mint">"text-foreground/50 italic"># CSV should have: UserPrincipalName, Department, JobTitle, OfficeLocation, MobilePhone
5$Updates = Import-Csv -Path class="text-pastel-mint">"C:\Updates\UserAttributes.csv"
6
7foreach ($Update in $Updates) {
8 try {
9 $User = Get-MgUser -Filter class="text-pastel-mint">"userPrincipalName eq '$($Update.UserPrincipalName)class="text-pastel-mint">'"
10
11 if ($User) {
12 $UpdateParams = @{}
13
14 if ($Update.Department) { $UpdateParams[class="text-pastel-mint">'Department'] = $Update.Department }
15 if ($Update.JobTitle) { $UpdateParams[class="text-pastel-mint">'JobTitle'] = $Update.JobTitle }
16 if ($Update.OfficeLocation) { $UpdateParams[class="text-pastel-mint">'OfficeLocation'] = $Update.OfficeLocation }
17 if ($Update.MobilePhone) { $UpdateParams[class="text-pastel-mint">'MobilePhone'] = $Update.MobilePhone }
18
19 Update-MgUser -UserId $User.Id @UpdateParams
20 Write-Host class="text-pastel-mint">"Updated: $($User.DisplayName)" -ForegroundColor Green
21 } else {
22 Write-Host class="text-pastel-mint">"User not found: $($Update.UserPrincipalName)" -ForegroundColor Yellow
23 }
24 } catch {
25 Write-Host class="text-pastel-mint">"Error updating $($Update.UserPrincipalName): $($_.Exception.Message)" -ForegroundColor Red
26 }
27}
28
29Write-Host class="text-pastel-mint">"Attribute sync completed" -ForegroundColor Cyan
Click the buttons above to copy or download

Export RBAC Role Assignments

Generate comprehensive report of all RBAC role assignments

Advanced
IAMScript #31
export-rbac-assignments.ps1powershell
1class=class="text-pastel-mint">"text-foreground/50 italic"># Export all RBAC role assignments
2Connect-MgGraph -Scopes class="text-pastel-mint">"RoleManagement.Read.Directory", class="text-pastel-mint">"Directory.Read.All"
3
4$RoleDefinitions = Get-MgRoleManagementDirectoryRoleDefinition -All
5$Report = @()
6
7foreach ($Role in $RoleDefinitions) {
8 Write-Host class="text-pastel-mint">"Processing: $($Role.DisplayName)" -ForegroundColor Cyan
9
10 $Assignments = Get-MgRoleManagementDirectoryRoleAssignment -Filter class="text-pastel-mint">"roleDefinitionId eq '$($Role.Id)class="text-pastel-mint">'" -All
11
12 foreach ($Assignment in $Assignments) {
13 try {
14 $Principal = Get-MgDirectoryObject -DirectoryObjectId $Assignment.PrincipalId
15
16 $Report += [PSCustomObject]@{
17 RoleName = $Role.DisplayName
18 RoleDescription = $Role.Description
19 PrincipalName = $Principal.AdditionalProperties.displayName
20 PrincipalType = $Principal.AdditionalProperties.class="text-pastel-mint">'@odata.type' -replace class="text-pastel-mint">'class="text-foreground/50 italicclass="text-pastel-mint">">#microsoft.graph.', class="text-pastel-mint">''
21 PrincipalId = $Assignment.PrincipalId
22 AssignedDate = $Assignment.CreatedDateTime
23 DirectoryScopeId = $Assignment.DirectoryScopeId
24 }
25 } catch {
26 Write-Host class="text-pastel-mint">"Error processing assignment: $($Assignment.Id)" -ForegroundColor Yellow
27 }
28 }
29}
30
31Write-Host class="text-pastel-mint">"Total assignments: $($Report.Count)" -ForegroundColor Green
32$Report | Export-Csv -Path class="text-pastel-mint">"RBACAssignments_$(Get-Date -Format 'yyyyMMddclass="text-pastel-mint">').csv" -NoTypeInformation
33$Report | Format-Table RoleName, PrincipalName, PrincipalType -AutoSize
Click the buttons above to copy or download

Monitor OAuth Consent Grants

Audit OAuth2 permission grants and identify potential security risks

Advanced
SecurityScript #32
monitor-consent-grants.ps1powershell
1class=class="text-pastel-mint">"text-foreground/50 italic"># Monitor OAuth consent grants
2Connect-MgGraph -Scopes class="text-pastel-mint">"Directory.Read.All", class="text-pastel-mint">"DelegatedPermissionGrant.ReadWrite.All"
3
4$ConsentGrants = Get-MgOauth2PermissionGrant -All
5$Report = @()
6
7foreach ($Grant in $ConsentGrants) {
8 try {
9 $ServicePrincipal = Get-MgServicePrincipal -ServicePrincipalId $Grant.ClientId
10 $Principal = if ($Grant.PrincipalId) { Get-MgUser -UserId $Grant.PrincipalId } else { $null }
11
12 $Report += [PSCustomObject]@{
13 ApplicationName = $ServicePrincipal.DisplayName
14 ApplicationId = $ServicePrincipal.AppId
15 ConsentType = $Grant.ConsentType
16 PrincipalName = if ($Principal) { $Principal.DisplayName } else { class="text-pastel-mint">"All Users" }
17 Scope = $Grant.Scope
18 ExpiryTime = $Grant.ExpiryTime
19 StartTime = $Grant.StartTime
20 }
21 } catch {
22 Write-Host class="text-pastel-mint">"Error processing grant: $($Grant.Id)" -ForegroundColor Yellow
23 }
24}
25
26class=class="text-pastel-mint">"text-foreground/50 italic"># Identify high-risk permissions
27$HighRiskScopes = class="text-pastel-mint">"Mail.Read", class="text-pastel-mint">"Files.ReadWrite", class="text-pastel-mint">"User.ReadWrite.All"
28$RiskyGrants = $Report | Where-Object {
29 $Scope = $_.Scope
30 $HighRiskScopes | Where-Object { $Scope -like class="text-pastel-mint">"*$_*" }
31}
32
33Write-Host class="text-pastel-mint">"Total consent grants: $($Report.Count)" -ForegroundColor Cyan
34Write-Host class="text-pastel-mint">"High-risk grants: $($RiskyGrants.Count)" -ForegroundColor Yellow
35
36$Report | Export-Csv -Path class="text-pastel-mint">"ConsentGrants_$(Get-Date -Format 'yyyyMMddclass="text-pastel-mint">').csv" -NoTypeInformation
Click the buttons above to copy or download

Manage Deleted Users Recycle Bin

Review and permanently delete or restore users from recycle bin

Beginner
Entra ID ManagementScript #33
cleanup-deleted-users.ps1powershell
1class=class="text-pastel-mint">"text-foreground/50 italic"># Manage deleted users in recycle bin
2Connect-MgGraph -Scopes class="text-pastel-mint">"User.ReadWrite.All"
3
4class=class="text-pastel-mint">"text-foreground/50 italic"># Get deleted users (in recycle bin)
5$DeletedUsers = Get-MgDirectoryDeletedItem -DirectoryObjectId microsoft.graph.user -All
6
7Write-Host class="text-pastel-mint">"Found $($DeletedUsers.Count) deleted users in recycle bin" -ForegroundColor Yellow
8
9$DeletedReport = $DeletedUsers | ForEach-Object {
10 [PSCustomObject]@{
11 DisplayName = $_.AdditionalProperties.displayName
12 UserPrincipalName = $_.AdditionalProperties.userPrincipalName
13 DeletedDateTime = $_.DeletedDateTime
14 DaysInRecycleBin = ((Get-Date) - $_.DeletedDateTime).Days
15 Id = $_.Id
16 }
17}
18
19$DeletedReport | Sort-Object DaysInRecycleBin -Descending | Format-Table -AutoSize
20
21class=class="text-pastel-mint">"text-foreground/50 italic"># Restore a user (example)
22class=class="text-pastel-mint">"text-foreground/50 italic"># Restore-MgDirectoryDeletedItem -DirectoryObjectId class="text-pastel-mint">"user-id-here"
23
24class=class="text-pastel-mint">"text-foreground/50 italic"># Permanently delete a user (example)
25class=class="text-pastel-mint">"text-foreground/50 italic"># Remove-MgDirectoryDeletedItem -DirectoryObjectId class="text-pastel-mint">"user-id-here"
26
27Write-Host class="text-pastel-mint">"`nUsers will be auto-deleted after 30 days" -ForegroundColor Cyan
28$DeletedReport | Export-Csv -Path class="text-pastel-mint">"DeletedUsers_$(Get-Date -Format 'yyyyMMddclass="text-pastel-mint">').csv" -NoTypeInformation
Click the buttons above to copy or download

Audit All Directory Role Assignments

Comprehensive audit of directory roles and their members

Intermediate
IAMScript #34
audit-directory-roles.ps1powershell
1class=class="text-pastel-mint">"text-foreground/50 italic"># Audit directory role assignments
2Connect-MgGraph -Scopes class="text-pastel-mint">"Directory.Read.All", class="text-pastel-mint">"RoleManagement.Read.All"
3
4$DirectoryRoles = Get-MgDirectoryRole -All
5$RoleReport = @()
6
7foreach ($Role in $DirectoryRoles) {
8 Write-Host class="text-pastel-mint">"Processing: $($Role.DisplayName)" -ForegroundColor Cyan
9
10 $Members = Get-MgDirectoryRoleMember -DirectoryRoleId $Role.Id -All
11
12 if ($Members.Count -eq 0) {
13 $RoleReport += [PSCustomObject]@{
14 RoleName = $Role.DisplayName
15 RoleDescription = $Role.Description
16 MemberName = class="text-pastel-mint">"No members"
17 MemberType = class="text-pastel-mint">"N/A"
18 MemberUPN = class="text-pastel-mint">"N/A"
19 }
20 } else {
21 foreach ($Member in $Members) {
22 $RoleReport += [PSCustomObject]@{
23 RoleName = $Role.DisplayName
24 RoleDescription = $Role.Description
25 MemberName = $Member.AdditionalProperties.displayName
26 MemberType = $Member.AdditionalProperties.class="text-pastel-mint">'@odata.type' -replace class="text-pastel-mint">'class="text-foreground/50 italicclass="text-pastel-mint">">#microsoft.graph.', class="text-pastel-mint">''
27 MemberUPN = $Member.AdditionalProperties.userPrincipalName
28 }
29 }
30 }
31}
32
33Write-Host class="text-pastel-mint">"`nTotal roles: $($DirectoryRoles.Count)" -ForegroundColor Green
34Write-Host class="text-pastel-mint">"Total assignments: $(($RoleReport | Where-Object MemberName -ne 'No membersclass="text-pastel-mint">').Count)" -ForegroundColor Green
35
36$RoleReport | Export-Csv -Path class="text-pastel-mint">"DirectoryRoles_$(Get-Date -Format 'yyyyMMddclass="text-pastel-mint">').csv" -NoTypeInformation
37$RoleReport | Format-Table RoleName, MemberName, MemberType -AutoSize
Click the buttons above to copy or download

Enforce Group Naming Policy

Validate and enforce naming conventions for Entra ID groups

Intermediate
ComplianceScript #35
enforce-naming-policy.ps1powershell
1class=class="text-pastel-mint">"text-foreground/50 italic"># Enforce group naming policy
2Connect-MgGraph -Scopes class="text-pastel-mint">"Group.Read.All"
3
4class=class="text-pastel-mint">"text-foreground/50 italic"># Define naming convention: [Type]-[Department]-[Purpose]
5$NamingPattern = class="text-pastel-mint">"^(Security|M365|Distribution)-(IT|HR|Finance|Sales|Marketing)-[A-Za-z0-9]+$"
6
7$AllGroups = Get-MgGroup -All
8$NonCompliantGroups = @()
9
10foreach ($Group in $AllGroups) {
11 if ($Group.DisplayName -notmatch $NamingPattern) {
12 $NonCompliantGroups += [PSCustomObject]@{
13 GroupName = $Group.DisplayName
14 GroupId = $Group.Id
15 GroupType = if ($Group.SecurityEnabled) { class="text-pastel-mint">"Security" } else { class="text-pastel-mint">"Microsoft 365" }
16 CreatedDateTime = $Group.CreatedDateTime
17 ExpectedFormat = class="text-pastel-mint">"[Type]-[Department]-[Purpose]"
18 }
19 }
20}
21
22Write-Host class="text-pastel-mint">"Total Groups: $($AllGroups.Count)" -ForegroundColor Cyan
23Write-Host class="text-pastel-mint">"Compliant: $(($AllGroups.Count - $NonCompliantGroups.Count))" -ForegroundColor Green
24Write-Host class="text-pastel-mint">"Non-Compliant: $($NonCompliantGroups.Count)" -ForegroundColor Red
25
26if ($NonCompliantGroups.Count -gt 0) {
27 Write-Host class="text-pastel-mint">"`nNon-Compliant Groups:" -ForegroundColor Yellow
28 $NonCompliantGroups | Format-Table GroupName, GroupType, ExpectedFormat -AutoSize
29 $NonCompliantGroups | Export-Csv -Path class="text-pastel-mint">"NonCompliantGroups_$(Get-Date -Format 'yyyyMMddclass="text-pastel-mint">').csv" -NoTypeInformation
30}
Click the buttons above to copy or download

Monitor Privileged Access Usage

Track usage of privileged roles and generate compliance reports

Advanced
ComplianceScript #36
monitor-privileged-access.ps1powershell
1class=class="text-pastel-mint">"text-foreground/50 italic"># Monitor privileged access usage
2Connect-MgGraph -Scopes class="text-pastel-mint">"AuditLog.Read.All", class="text-pastel-mint">"Directory.Read.All", class="text-pastel-mint">"RoleManagement.Read.All"
3
4$StartDate = (Get-Date).AddDays(-7)
5$PrivilegedRoles = Get-MgDirectoryRole | Where-Object { $_.DisplayName -like class="text-pastel-mint">"*Admin*" }
6$Report = @()
7
8foreach ($Role in $PrivilegedRoles) {
9 $Members = Get-MgDirectoryRoleMember -DirectoryRoleId $Role.Id
10
11 foreach ($Member in $Members) {
12 try {
13 $User = Get-MgUser -UserId $Member.Id -Property DisplayName, UserPrincipalName, SignInActivity
14
15 class=class="text-pastel-mint">"text-foreground/50 italic"># Get audit logs for this user
16 $AuditLogs = Get-MgAuditLogSignIn -Filter class="text-pastel-mint">"userId eq '$($User.Id)class="text-pastel-mint">' and createdDateTime ge $($StartDate.ToString('yyyy-MM-ddclass="text-pastel-mint">'))" -Top 50
17
18 $Report += [PSCustomObject]@{
19 RoleName = $Role.DisplayName
20 UserName = $User.DisplayName
21 UserPrincipalName = $User.UserPrincipalName
22 LastSignIn = $User.SignInActivity.LastSignInDateTime
23 SignInCount = $AuditLogs.Count
24 LastActivity = if ($AuditLogs) { ($AuditLogs | Sort-Object CreatedDateTime -Descending | Select-Object -First 1).CreatedDateTime } else { class="text-pastel-mint">"No activity" }
25 }
26 } catch {
27 Write-Host class="text-pastel-mint">"Error processing user: $($Member.Id)" -ForegroundColor Yellow
28 }
29 }
30}
31
32Write-Host class="text-pastel-mint">"Privileged Access Report (Last 7 Days)" -ForegroundColor Cyan
33$Report | Export-Csv -Path class="text-pastel-mint">"PrivilegedAccess_$(Get-Date -Format 'yyyyMMddclass="text-pastel-mint">').csv" -NoTypeInformation
34$Report | Format-Table -AutoSize
Click the buttons above to copy or download

Configure External Identity Settings

Manage B2B collaboration and external identity provider settings

Advanced
IAMScript #37
configure-external-identities.ps1powershell
1class=class="text-pastel-mint">"text-foreground/50 italic"># Configure external identity settings
2Connect-MgGraph -Scopes class="text-pastel-mint">"Policy.ReadWrite.CrossTenantAccess", class="text-pastel-mint">"Policy.Read.All"
3
4class=class="text-pastel-mint">"text-foreground/50 italic"># Get current cross-tenant access settings
5$CrossTenantPolicy = Get-MgPolicyCrossTenantAccessPolicyDefault
6
7Write-Host class="text-pastel-mint">"Current External Identity Settings:" -ForegroundColor Cyan
8Write-Host class="text-pastel-mint">"Inbound Trust:" -ForegroundColor Yellow
9Write-Host class="text-pastel-mint">" MFA Trusted: $($CrossTenantPolicy.InboundTrust.IsMfaAccepted)" -ForegroundColor White
10Write-Host class="text-pastel-mint">" Compliant Device Trusted: $($CrossTenantPolicy.InboundTrust.IsCompliantDeviceAccepted)" -ForegroundColor White
11Write-Host class="text-pastel-mint">" Hybrid Azure AD Joined Trusted: $($CrossTenantPolicy.InboundTrust.IsHybridAzureADJoinedDeviceAccepted)" -ForegroundColor White
12
13class=class="text-pastel-mint">"text-foreground/50 italic"># Update settings (example)
14$UpdateParams = @{
15 InboundTrust = @{
16 IsMfaAccepted = $true
17 IsCompliantDeviceAccepted = $true
18 IsHybridAzureADJoinedDeviceAccepted = $true
19 }
20}
21
22try {
23 Update-MgPolicyCrossTenantAccessPolicyDefault -BodyParameter $UpdateParams
24 Write-Host class="text-pastel-mint">"`nExternal identity settings updated successfully" -ForegroundColor Green
25} catch {
26 Write-Host class="text-pastel-mint">"Error: $($_.Exception.Message)" -ForegroundColor Red
27}
28
29class=class="text-pastel-mint">"text-foreground/50 italic"># List external collaboration restrictions
30Write-Host class="text-pastel-mint">"`nB2B Collaboration Status:" -ForegroundColor Cyan
31Write-Host class="text-pastel-mint">"Guest users can be invited and can collaborate" -ForegroundColor Green
Click the buttons above to copy or download

Track License Assignment Changes

Monitor and report license assignment changes over time

Intermediate
ComplianceScript #38
report-license-changes.ps1powershell
1class=class="text-pastel-mint">"text-foreground/50 italic"># Track license assignment changes
2Connect-MgGraph -Scopes class="text-pastel-mint">"AuditLog.Read.All", class="text-pastel-mint">"Directory.Read.All"
3
4$StartDate = (Get-Date).AddDays(-30)
5
6class=class="text-pastel-mint">"text-foreground/50 italic"># Get audit logs for license changes
7$AuditLogs = Get-MgAuditLogDirectoryAudit -Filter class="text-pastel-mint">"activityDateTime ge $($StartDate.ToString('yyyy-MM-ddclass="text-pastel-mint">')) and category eq 'UserManagementclass="text-pastel-mint">'" -All
8
9$LicenseChanges = $AuditLogs | Where-Object {
10 $_.TargetResources.ModifiedProperties.DisplayName -contains class="text-pastel-mint">"AssignedLicense"
11}
12
13$Report = foreach ($Log in $LicenseChanges) {
14 [PSCustomObject]@{
15 DateTime = $Log.ActivityDateTime
16 Activity = $Log.ActivityDisplayName
17 InitiatedBy = $Log.InitiatedBy.User.UserPrincipalName
18 TargetUser = $Log.TargetResources[0].UserPrincipalName
19 TargetUserName = $Log.TargetResources[0].DisplayName
20 Result = $Log.Result
21 }
22}
23
24Write-Host class="text-pastel-mint">"License Changes (Last 30 Days)" -ForegroundColor Cyan
25Write-Host class="text-pastel-mint">"Total Changes: $($Report.Count)" -ForegroundColor Yellow
26
27$Report | Sort-Object DateTime -Descending | Format-Table -AutoSize
28$Report | Export-Csv -Path class="text-pastel-mint">"LicenseChanges_$(Get-Date -Format 'yyyyMMddclass="text-pastel-mint">').csv" -NoTypeInformation
Click the buttons above to copy or download

Validate User Profile Data Quality

Check for incomplete or missing user profile information

Beginner
Entra ID ManagementScript #39
validate-user-data.ps1powershell
1class=class="text-pastel-mint">"text-foreground/50 italic"># Validate user profile data quality
2Connect-MgGraph -Scopes class="text-pastel-mint">"User.Read.All"
3
4$Users = Get-MgUser -All -Property DisplayName, UserPrincipalName, Department, JobTitle, MobilePhone, OfficeLocation, Manager
5
6$IncompleteProfiles = $Users | Where-Object {
7 -not $_.Department -or
8 -not $_.JobTitle -or
9 -not $_.MobilePhone -or
10 -not $_.OfficeLocation
11} | Select-Object DisplayName, UserPrincipalName,
12 @{Name=class="text-pastel-mint">'MissingDepartment';Expression={-not $_.Department}},
13 @{Name=class="text-pastel-mint">'MissingJobTitle';Expression={-not $_.JobTitle}},
14 @{Name=class="text-pastel-mint">'MissingMobilePhone';Expression={-not $_.MobilePhone}},
15 @{Name=class="text-pastel-mint">'MissingOfficeLocation';Expression={-not $_.OfficeLocation}},
16 @{Name=class="text-pastel-mint">'MissingFieldCount';Expression={
17 $count = 0
18 if (-not $_.Department) { $count++ }
19 if (-not $_.JobTitle) { $count++ }
20 if (-not $_.MobilePhone) { $count++ }
21 if (-not $_.OfficeLocation) { $count++ }
22 $count
23 }}
24
25Write-Host class="text-pastel-mint">"Data Quality Report:" -ForegroundColor Cyan
26Write-Host class="text-pastel-mint">"Total Users: $($Users.Count)" -ForegroundColor White
27Write-Host class="text-pastel-mint">"Incomplete Profiles: $($IncompleteProfiles.Count)" -ForegroundColor Yellow
28Write-Host class="text-pastel-mint">"Complete Profiles: $(($Users.Count - $IncompleteProfiles.Count))" -ForegroundColor Green
29
30$IncompleteProfiles | Sort-Object MissingFieldCount -Descending | Export-Csv -Path class="text-pastel-mint">"IncompleteProfiles_$(Get-Date -Format 'yyyyMMddclass="text-pastel-mint">').csv" -NoTypeInformation
31$IncompleteProfiles | Format-Table -AutoSize
Click the buttons above to copy or download

Configure Emergency Access Accounts

Set up and monitor break-glass emergency access accounts

Advanced
SecurityScript #40
manage-emergency-access.ps1powershell
1class=class="text-pastel-mint">"text-foreground/50 italic"># Configure emergency access (break-glass) accounts
2Connect-MgGraph -Scopes class="text-pastel-mint">"User.ReadWrite.All", class="text-pastel-mint">"RoleManagement.ReadWrite.Directory"
3
4class=class="text-pastel-mint">"text-foreground/50 italic"># Emergency access account configuration
5$EmergencyAccounts = @(
6 class="text-pastel-mint">"emergencyaccess1@yourdomain.com",
7 class="text-pastel-mint">"emergencyaccess2@yourdomain.com"
8)
9
10Write-Host class="text-pastel-mint">"Emergency Access Account Configuration" -ForegroundColor Cyan
11
12foreach ($AccountUPN in $EmergencyAccounts) {
13 try {
14 $User = Get-MgUser -Filter class="text-pastel-mint">"userPrincipalName eq '$AccountUPNclass="text-pastel-mint">'"
15
16 if ($User) {
17 class=class="text-pastel-mint">"text-foreground/50 italic"># Verify account settings
18 Write-Host class="text-pastel-mint">"`nAccount: $($User.DisplayName)" -ForegroundColor Yellow
19 Write-Host class="text-pastel-mint">" Enabled: $($User.AccountEnabled)" -ForegroundColor White
20 Write-Host class="text-pastel-mint">" Password Never Expires: Check manually" -ForegroundColor White
21
22 class=class="text-pastel-mint">"text-foreground/50 italic"># Check role assignments
23 $Roles = Get-MgUserMemberOf -UserId $User.Id | Where-Object {
24 $_.AdditionalProperties.class="text-pastel-mint">'@odata.type' -eq class="text-pastel-mint">'class="text-foreground/50 italicclass="text-pastel-mint">">#microsoft.graph.directoryRole'
25 }
26
27 Write-Host class="text-pastel-mint">" Assigned Roles: $($Roles.Count)" -ForegroundColor White
28 $Roles | ForEach-Object { Write-Host class="text-pastel-mint">" - $($_.AdditionalProperties.displayName)" -ForegroundColor Cyan }
29
30 class=class="text-pastel-mint">"text-foreground/50 italic"># Check last sign-in
31 $SignIn = $User.SignInActivity.LastSignInDateTime
32 if ($SignIn) {
33 $DaysSinceSignIn = ((Get-Date) - $SignIn).Days
34 Write-Host class="text-pastel-mint">" Last Sign-In: $SignIn ($DaysSinceSignIn days ago)" -ForegroundColor $(if ($DaysSinceSignIn -lt 90) { class="text-pastel-mint">'Red' } else { class="text-pastel-mint">'Green' })
35 }
36 }
37 } catch {
38 Write-Host class="text-pastel-mint">"Error checking $AccountUPN : $($_.Exception.Message)" -ForegroundColor Red
39 }
40}
41
42Write-Host class="text-pastel-mint">"`nBest Practices:" -ForegroundColor Green
43Write-Host class="text-pastel-mint">"- Store credentials in secure physical location" -ForegroundColor White
44Write-Host class="text-pastel-mint">"- Exclude from MFA requirements" -ForegroundColor White
45Write-Host class="text-pastel-mint">"- Exclude from Conditional Access policies" -ForegroundColor White
46Write-Host class="text-pastel-mint">"- Monitor for any usage" -ForegroundColor White
Click the buttons above to copy or download

Export Detailed User License Report

Generate detailed report of license assignments per user

Intermediate
Entra ID ManagementScript #41
export-user-licenses.ps1powershell
1class=class="text-pastel-mint">"text-foreground/50 italic"># Export detailed user license report
2Connect-MgGraph -Scopes class="text-pastel-mint">"User.Read.All", class="text-pastel-mint">"Organization.Read.All"
3
4$Users = Get-MgUser -All -Property DisplayName, UserPrincipalName, AssignedLicenses, Department, AccountEnabled
5$SKUs = Get-MgSubscribedSku
6$Report = @()
7
8foreach ($User in $Users) {
9 if ($User.AssignedLicenses.Count -gt 0) {
10 foreach ($License in $User.AssignedLicenses) {
11 $SKU = $SKUs | Where-Object { $_.SkuId -eq $License.SkuId }
12
13 $Report += [PSCustomObject]@{
14 DisplayName = $User.DisplayName
15 UserPrincipalName = $User.UserPrincipalName
16 Department = $User.Department
17 AccountEnabled = $User.AccountEnabled
18 LicenseName = $SKU.SkuPartNumber
19 LicenseId = $License.SkuId
20 DisabledPlans = $License.DisabledPlans.Count
21 }
22 }
23 } else {
24 $Report += [PSCustomObject]@{
25 DisplayName = $User.DisplayName
26 UserPrincipalName = $User.UserPrincipalName
27 Department = $User.Department
28 AccountEnabled = $User.AccountEnabled
29 LicenseName = class="text-pastel-mint">"No License"
30 LicenseId = class="text-pastel-mint">"N/A"
31 DisabledPlans = 0
32 }
33 }
34}
35
36Write-Host class="text-pastel-mint">"User License Report" -ForegroundColor Cyan
37Write-Host class="text-pastel-mint">"Total Users: $($Users.Count)" -ForegroundColor White
38Write-Host class="text-pastel-mint">"Licensed Users: $(($Report | Where-Object LicenseName -ne 'No Licenseclass="text-pastel-mint">' | Select-Object -Unique UserPrincipalName).Count)" -ForegroundColor Green
39Write-Host class="text-pastel-mint">"Unlicensed Users: $(($Report | Where-Object LicenseName -eq 'No Licenseclass="text-pastel-mint">').Count)" -ForegroundColor Yellow
40
41$Report | Export-Csv -Path class="text-pastel-mint">"UserLicenses_$(Get-Date -Format 'yyyyMMddclass="text-pastel-mint">').csv" -NoTypeInformation
Click the buttons above to copy or download

Audit Conditional Access Policy Usage

Analyze which Conditional Access policies are being triggered

Advanced
SecurityScript #42
audit-conditional-access-usage.ps1powershell
1class=class="text-pastel-mint">"text-foreground/50 italic"># Audit Conditional Access policy usage
2Connect-MgGraph -Scopes class="text-pastel-mint">"Policy.Read.All", class="text-pastel-mint">"AuditLog.Read.All"
3
4$StartDate = (Get-Date).AddDays(-7)
5$SignIns = Get-MgAuditLogSignIn -Filter class="text-pastel-mint">"createdDateTime ge $($StartDate.ToString('yyyy-MM-ddclass="text-pastel-mint">'))" -Top 1000
6
7class=class="text-pastel-mint">"text-foreground/50 italic"># Analyze CA policy results
8$CAResults = $SignIns | Where-Object { $_.ConditionalAccessStatus -ne class="text-pastel-mint">'notApplied' } |
9 Select-Object -ExpandProperty AppliedConditionalAccessPolicies
10
11$PolicyStats = $CAResults | Group-Object DisplayName | ForEach-Object {
12 [PSCustomObject]@{
13 PolicyName = $_.Name
14 TimesApplied = $_.Count
15 SuccessCount = ($_.Group | Where-Object Result -eq class="text-pastel-mint">'success').Count
16 FailureCount = ($_.Group | Where-Object Result -eq class="text-pastel-mint">'failure').Count
17 NotAppliedCount = ($_.Group | Where-Object Result -eq class="text-pastel-mint">'notApplied').Count
18 }
19} | Sort-Object TimesApplied -Descending
20
21Write-Host class="text-pastel-mint">"Conditional Access Policy Usage (Last 7 Days)" -ForegroundColor Cyan
22Write-Host class="text-pastel-mint">"Total Sign-Ins Analyzed: $($SignIns.Count)" -ForegroundColor White
23Write-Host class="text-pastel-mint">"Sign-Ins with CA Applied: $(($SignIns | Where-Object ConditionalAccessStatus -ne 'notAppliedclass="text-pastel-mint">').Count)" -ForegroundColor Yellow
24
25$PolicyStats | Format-Table -AutoSize
26$PolicyStats | Export-Csv -Path class="text-pastel-mint">"CAPolicyUsage_$(Get-Date -Format 'yyyyMMddclass="text-pastel-mint">').csv" -NoTypeInformation
Click the buttons above to copy or download

Bulk Disable User Accounts

Disable multiple user accounts from CSV for offboarding

Beginner
Entra ID ManagementScript #43
bulk-disable-users.ps1powershell
1class=class="text-pastel-mint">"text-foreground/50 italic"># Bulk disable user accounts
2Connect-MgGraph -Scopes class="text-pastel-mint">"User.ReadWrite.All"
3
4class=class="text-pastel-mint">"text-foreground/50 italic"># CSV should have column: UserPrincipalName
5$UsersToDisable = Import-Csv -Path class="text-pastel-mint">"C:\Offboarding\UsersToDisable.csv"
6
7Write-Host class="text-pastel-mint">"Processing $($UsersToDisable.Count) users for disabling..." -ForegroundColor Yellow
8
9foreach ($Item in $UsersToDisable) {
10 try {
11 $User = Get-MgUser -Filter class="text-pastel-mint">"userPrincipalName eq '$($Item.UserPrincipalName)class="text-pastel-mint">'"
12
13 if ($User) {
14 if ($User.AccountEnabled -eq $true) {
15 Update-MgUser -UserId $User.Id -AccountEnabled $false
16
17 class=class="text-pastel-mint">"text-foreground/50 italic"># Revoke sessions
18 Revoke-MgUserSignInSession -UserId $User.Id
19
20 Write-Host class="text-pastel-mint">"Disabled: $($User.DisplayName) - Sessions revoked" -ForegroundColor Yellow
21 } else {
22 Write-Host class="text-pastel-mint">"Already disabled: $($User.DisplayName)" -ForegroundColor Cyan
23 }
24 } else {
25 Write-Host class="text-pastel-mint">"User not found: $($Item.UserPrincipalName)" -ForegroundColor Red
26 }
27 } catch {
28 Write-Host class="text-pastel-mint">"Error disabling $($Item.UserPrincipalName): $($_.Exception.Message)" -ForegroundColor Red
29 }
30}
31
32Write-Host class="text-pastel-mint">"`nBulk disable operation completed" -ForegroundColor Green
Click the buttons above to copy or download

Manage Dynamic Group Rules

Create and test dynamic membership rules for groups

Advanced
IAMScript #44
manage-dynamic-group-rules.ps1powershell
1class=class="text-pastel-mint">"text-foreground/50 italic"># Manage dynamic group membership rules
2Connect-MgGraph -Scopes class="text-pastel-mint">"Group.ReadWrite.All", class="text-pastel-mint">"User.Read.All"
3
4function Test-DynamicGroupRule {
5 param(
6 [string]$MembershipRule
7 )
8
9 Write-Host class="text-pastel-mint">"`nTesting rule: $MembershipRule" -ForegroundColor Cyan
10
11 class=class="text-pastel-mint">"text-foreground/50 italic"># Sample test: Get users that would match
12 class=class="text-pastel-mint">"text-foreground/50 italic"># Note: Actual validation requires implementing rule parser
13 Write-Host class="text-pastel-mint">"Rule syntax appears valid" -ForegroundColor Green
14 return $true
15}
16
17class=class="text-pastel-mint">"text-foreground/50 italic"># Common dynamic group rule examples
18$RuleExamples = @(
19 @{
20 Name = class="text-pastel-mint">"All IT Department Users"
21 Rule = class="text-pastel-mint">'(user.department -eq "ITclass="text-pastel-mint">") and (user.accountEnabled -eq true)'
22 },
23 @{
24 Name = class="text-pastel-mint">"Managers Only"
25 Rule = class="text-pastel-mint">'(user.jobTitle -contains "Managerclass="text-pastel-mint">") and (user.accountEnabled -eq true)'
26 },
27 @{
28 Name = class="text-pastel-mint">"Sales Team with Licenses"
29 Rule = class="text-pastel-mint">'(user.department -eq "Salesclass="text-pastel-mint">") and (user.assignedLicenses -any (assignedLicenses/any(s:s/skuId -eq "license-guidclass="text-pastel-mint">")))'
30 },
31 @{
32 Name = class="text-pastel-mint">"Users in Specific Location"
33 Rule = class="text-pastel-mint">'(user.country -eq "United Statesclass="text-pastel-mint">") and (user.usageLocation -eq "USclass="text-pastel-mint">")'
34 }
35)
36
37Write-Host class="text-pastel-mint">"Dynamic Group Rule Examples:" -ForegroundColor Cyan
38
39foreach ($Example in $RuleExamples) {
40 Write-Host class="text-pastel-mint">"`n$($Example.Name):" -ForegroundColor Yellow
41 Write-Host class="text-pastel-mint">" $($Example.Rule)" -ForegroundColor White
42 Test-DynamicGroupRule -MembershipRule $Example.Rule
43}
44
45Write-Host class="text-pastel-mint">"`nUse these rules when creating dynamic groups with New-MgGroup" -ForegroundColor Green
Click the buttons above to copy or download

Export User Authentication Methods

Report on all authentication methods registered by users

Intermediate
SecurityScript #45
export-authentication-methods.ps1powershell
1class=class="text-pastel-mint">"text-foreground/50 italic"># Export user authentication methods
2Connect-MgGraph -Scopes class="text-pastel-mint">"UserAuthenticationMethod.Read.All", class="text-pastel-mint">"User.Read.All"
3
4$Users = Get-MgUser -All -Property DisplayName, UserPrincipalName | Select-Object -First 100
5$Report = @()
6
7foreach ($User in $Users) {
8 try {
9 $AuthMethods = Get-MgUserAuthenticationMethod -UserId $User.Id
10
11 $Methods = @{
12 Password = $false
13 Phone = $false
14 Email = $false
15 Authenticator = $false
16 FIDO2 = $false
17 WindowsHello = $false
18 }
19
20 foreach ($Method in $AuthMethods) {
21 $MethodType = $Method.AdditionalProperties.class="text-pastel-mint">'@odata.type'
22
23 switch -Wildcard ($MethodType) {
24 class="text-pastel-mint">'*password*' { $Methods.Password = $true }
25 class="text-pastel-mint">'*phone*' { $Methods.Phone = $true }
26 class="text-pastel-mint">'*email*' { $Methods.Email = $true }
27 class="text-pastel-mint">'*microsoftAuthenticator*' { $Methods.Authenticator = $true }
28 class="text-pastel-mint">'*fido2*' { $Methods.FIDO2 = $true }
29 class="text-pastel-mint">'*windowsHello*' { $Methods.WindowsHello = $true }
30 }
31 }
32
33 $Report += [PSCustomObject]@{
34 DisplayName = $User.DisplayName
35 UserPrincipalName = $User.UserPrincipalName
36 TotalMethods = $AuthMethods.Count
37 Password = $Methods.Password
38 Phone = $Methods.Phone
39 Email = $Methods.Email
40 Authenticator = $Methods.Authenticator
41 FIDO2 = $Methods.FIDO2
42 WindowsHello = $Methods.WindowsHello
43 }
44 } catch {
45 Write-Host class="text-pastel-mint">"Error processing: $($User.UserPrincipalName)" -ForegroundColor Yellow
46 }
47}
48
49$Report | Export-Csv -Path class="text-pastel-mint">"AuthMethods_$(Get-Date -Format 'yyyyMMddclass="text-pastel-mint">').csv" -NoTypeInformation
50Write-Host class="text-pastel-mint">"Authentication methods exported for $($Report.Count) users" -ForegroundColor Green
51$Report | Format-Table -AutoSize
Click the buttons above to copy or download

Monitor Administrative Activity

Track all administrative actions in Entra ID

Advanced
ComplianceScript #46
monitor-admin-activity.ps1powershell
1class=class="text-pastel-mint">"text-foreground/50 italic"># Monitor administrative activity
2Connect-MgGraph -Scopes class="text-pastel-mint">"AuditLog.Read.All", class="text-pastel-mint">"Directory.Read.All"
3
4$StartDate = (Get-Date).AddDays(-7)
5$AdminActivities = Get-MgAuditLogDirectoryAudit -Filter class="text-pastel-mint">"activityDateTime ge $($StartDate.ToString('yyyy-MM-ddclass="text-pastel-mint">'))" -All
6
7class=class="text-pastel-mint">"text-foreground/50 italic"># Focus on high-privilege activities
8$CriticalActivities = @(
9 class="text-pastel-mint">"Add member to role",
10 class="text-pastel-mint">"Remove member from role",
11 class="text-pastel-mint">"Update user",
12 class="text-pastel-mint">"Delete user",
13 class="text-pastel-mint">"Reset user password",
14 class="text-pastel-mint">"Add service principal",
15 class="text-pastel-mint">"Update policy"
16)
17
18$Report = $AdminActivities | Where-Object {
19 $_.ActivityDisplayName -in $CriticalActivities
20} | ForEach-Object {
21 [PSCustomObject]@{
22 DateTime = $_.ActivityDateTime
23 Activity = $_.ActivityDisplayName
24 InitiatedBy = $_.InitiatedBy.User.UserPrincipalName
25 TargetResource = $_.TargetResources[0].DisplayName
26 Result = $_.Result
27 Category = $_.Category
28 }
29} | Sort-Object DateTime -Descending
30
31Write-Host class="text-pastel-mint">"Administrative Activity Report (Last 7 Days)" -ForegroundColor Cyan
32Write-Host class="text-pastel-mint">"Total Admin Actions: $($Report.Count)" -ForegroundColor Yellow
33
34class=class="text-pastel-mint">"text-foreground/50 italic"># Group by initiator
35$ByAdmin = $Report | Group-Object InitiatedBy | Sort-Object Count -Descending
36
37Write-Host class="text-pastel-mint">"`nTop Administrators by Activity:" -ForegroundColor Yellow
38$ByAdmin | Select-Object Name, Count | Format-Table -AutoSize
39
40$Report | Export-Csv -Path class="text-pastel-mint">"AdminActivity_$(Get-Date -Format 'yyyyMMddclass="text-pastel-mint">').csv" -NoTypeInformation
Click the buttons above to copy or download

Configure Guest User Restrictions

Set granular permissions for guest user access

Advanced
SecurityScript #47
configure-guest-restrictions.ps1powershell
1class=class="text-pastel-mint">"text-foreground/50 italic"># Configure guest user restrictions
2Connect-MgGraph -Scopes class="text-pastel-mint">"Policy.ReadWrite.Authorization"
3
4class=class="text-pastel-mint">"text-foreground/50 italic"># Get current authorization policy
5$AuthPolicy = Get-MgPolicyAuthorizationPolicy
6
7Write-Host class="text-pastel-mint">"Current Guest User Restrictions:" -ForegroundColor Cyan
8Write-Host class="text-pastel-mint">"Guest User Role: $($AuthPolicy.GuestUserRoleId)" -ForegroundColor White
9Write-Host class="text-pastel-mint">"Allow Invitations From: $($AuthPolicy.AllowInvitesFrom)" -ForegroundColor White
10Write-Host class="text-pastel-mint">"Block MSOL PowerShell: $($AuthPolicy.BlockMsolPowerShell)" -ForegroundColor White
11
12class=class="text-pastel-mint">"text-foreground/50 italic"># Configure restrictive guest settings
13$GuestRestrictions = @{
14 class=class="text-pastel-mint">"text-foreground/50 italic"># Most restrictive: Guest users have limited access to properties and memberships
15 GuestUserRoleId = class="text-pastel-mint">"10dae51f-b6af-4016-8d66-8c2a99b929b3"
16
17 class=class="text-pastel-mint">"text-foreground/50 italic"># Only admins can invite
18 AllowInvitesFrom = class="text-pastel-mint">"adminsAndGuestInviters"
19
20 class=class="text-pastel-mint">"text-foreground/50 italic"># Disable MSOL PowerShell for guests
21 BlockMsolPowerShell = $true
22
23 class=class="text-pastel-mint">"text-foreground/50 italic"># Prevent guest users from creating tenants
24 DefaultUserRolePermissions = @{
25 AllowedToCreateApps = $false
26 AllowedToCreateSecurityGroups = $false
27 AllowedToReadOtherUsers = $true
28 }
29}
30
31try {
32 Write-Host class="text-pastel-mint">"`nApplying guest user restrictions..." -ForegroundColor Yellow
33 Update-MgPolicyAuthorizationPolicy -AuthorizationPolicyId $AuthPolicy.Id -BodyParameter $GuestRestrictions
34 Write-Host class="text-pastel-mint">"Guest restrictions updated successfully" -ForegroundColor Green
35
36 Write-Host class="text-pastel-mint">"`nRecommended Additional Steps:" -ForegroundColor Cyan
37 Write-Host class="text-pastel-mint">"1. Enable guest access reviews" -ForegroundColor White
38 Write-Host class="text-pastel-mint">"2. Set guest invite restrictions in Azure Portal" -ForegroundColor White
39 Write-Host class="text-pastel-mint">"3. Configure external collaboration settings" -ForegroundColor White
40
41} catch {
42 Write-Host class="text-pastel-mint">"Error: $($_.Exception.Message)" -ForegroundColor Red
43}
Click the buttons above to copy or download

Export Group Ownership Report

List all groups and their designated owners

Beginner
IAMScript #48
export-group-owners.ps1powershell
1class=class="text-pastel-mint">"text-foreground/50 italic"># Export group ownership report
2Connect-MgGraph -Scopes class="text-pastel-mint">"Group.Read.All", class="text-pastel-mint">"User.Read.All"
3
4$Groups = Get-MgGroup -All
5$Report = @()
6
7foreach ($Group in $Groups) {
8 $Owners = Get-MgGroupOwner -GroupId $Group.Id
9
10 if ($Owners.Count -eq 0) {
11 $Report += [PSCustomObject]@{
12 GroupName = $Group.DisplayName
13 GroupType = if ($Group.SecurityEnabled) { class="text-pastel-mint">"Security" } else { class="text-pastel-mint">"Microsoft 365" }
14 OwnerName = class="text-pastel-mint">"No Owner"
15 OwnerUPN = class="text-pastel-mint">"N/A"
16 MemberCount = (Get-MgGroupMember -GroupId $Group.Id -All).Count
17 }
18 } else {
19 foreach ($Owner in $Owners) {
20 $Report += [PSCustomObject]@{
21 GroupName = $Group.DisplayName
22 GroupType = if ($Group.SecurityEnabled) { class="text-pastel-mint">"Security" } else { class="text-pastel-mint">"Microsoft 365" }
23 OwnerName = $Owner.AdditionalProperties.displayName
24 OwnerUPN = $Owner.AdditionalProperties.userPrincipalName
25 MemberCount = (Get-MgGroupMember -GroupId $Group.Id -All).Count
26 }
27 }
28 }
29}
30
31$NoOwner = ($Report | Where-Object OwnerName -eq class="text-pastel-mint">"No Owner").Count
32
33Write-Host class="text-pastel-mint">"Group Ownership Report" -ForegroundColor Cyan
34Write-Host class="text-pastel-mint">"Total Groups: $($Groups.Count)" -ForegroundColor White
35Write-Host class="text-pastel-mint">"Groups Without Owners: $NoOwner" -ForegroundColor Yellow
36
37$Report | Export-Csv -Path class="text-pastel-mint">"GroupOwners_$(Get-Date -Format 'yyyyMMddclass="text-pastel-mint">').csv" -NoTypeInformation
38$Report | Format-Table GroupName, GroupType, OwnerName -AutoSize
Click the buttons above to copy or download

Audit User Consent Permissions

Review permissions users have consented to for applications

Advanced
SecurityScript #49
audit-user-consents.ps1powershell
1class=class="text-pastel-mint">"text-foreground/50 italic"># Audit user consent permissions
2Connect-MgGraph -Scopes class="text-pastel-mint">"DelegatedPermissionGrant.Read.All", class="text-pastel-mint">"User.Read.All", class="text-pastel-mint">"Application.Read.All"
3
4$ConsentGrants = Get-MgOauth2PermissionGrant -All
5$Report = @()
6
7foreach ($Grant in $ConsentGrants | Where-Object { $_.ConsentType -eq class="text-pastel-mint">'Principal' }) {
8 try {
9 $User = Get-MgUser -UserId $Grant.PrincipalId -Property DisplayName, UserPrincipalName
10 $ServicePrincipal = Get-MgServicePrincipal -ServicePrincipalId $Grant.ClientId
11
12 $Report += [PSCustomObject]@{
13 UserName = $User.DisplayName
14 UserPrincipalName = $User.UserPrincipalName
15 ApplicationName = $ServicePrincipal.DisplayName
16 ApplicationId = $ServicePrincipal.AppId
17 Permissions = $Grant.Scope
18 ConsentDate = $Grant.StartTime
19 ExpiryDate = $Grant.ExpiryTime
20 }
21 } catch {
22 Write-Host class="text-pastel-mint">"Error processing grant: $($Grant.Id)" -ForegroundColor Yellow
23 }
24}
25
26class=class="text-pastel-mint">"text-foreground/50 italic"># Identify risky consents
27$RiskyKeywords = @(class="text-pastel-mint">"Mail.Read", class="text-pastel-mint">"Files.ReadWrite", class="text-pastel-mint">"Mail.Send", class="text-pastel-mint">"Contacts.Read", class="text-pastel-mint">"Calendars.Read")
28$RiskyConsents = $Report | Where-Object {
29 $Permissions = $_.Permissions
30 $RiskyKeywords | Where-Object { $Permissions -like class="text-pastel-mint">"*$_*" }
31}
32
33Write-Host class="text-pastel-mint">"User Consent Audit" -ForegroundColor Cyan
34Write-Host class="text-pastel-mint">"Total User Consents: $($Report.Count)" -ForegroundColor White
35Write-Host class="text-pastel-mint">"Risky Consents: $($RiskyConsents.Count)" -ForegroundColor Yellow
36
37$Report | Export-Csv -Path class="text-pastel-mint">"UserConsents_$(Get-Date -Format 'yyyyMMddclass="text-pastel-mint">').csv" -NoTypeInformation
38$RiskyConsents | Format-Table UserName, ApplicationName, Permissions -AutoSize
Click the buttons above to copy or download

Manage Temporary Access Pass

Create temporary access passes for passwordless authentication

Intermediate
SecurityScript #50
manage-temp-access-pass.ps1powershell
1class=class="text-pastel-mint">"text-foreground/50 italic"># Manage Temporary Access Pass (TAP)
2Connect-MgGraph -Scopes class="text-pastel-mint">"UserAuthenticationMethod.ReadWrite.All"
3
4function New-TemporaryAccessPass {
5 param(
6 [Parameter(Mandatory=$true)]
7 [string]$UserPrincipalName,
8 [int]$LifetimeInMinutes = 60,
9 [switch]$OneTimeUse
10 )
11
12 try {
13 $User = Get-MgUser -Filter class="text-pastel-mint">"userPrincipalName eq '$UserPrincipalNameclass="text-pastel-mint">'"
14
15 $TapParams = @{
16 class="text-pastel-mint">"@odata.type" = class="text-pastel-mint">"class="text-foreground/50 italicclass="text-pastel-mint">">#microsoft.graph.temporaryAccessPassAuthenticationMethod"
17 lifetimeInMinutes = $LifetimeInMinutes
18 isUsableOnce = $OneTimeUse.IsPresent
19 }
20
21 $TAP = New-MgUserAuthenticationTemporaryAccessPassMethod -UserId $User.Id -BodyParameter $TapParams
22
23 Write-Host class="text-pastel-mint">"Temporary Access Pass Created" -ForegroundColor Green
24 Write-Host class="text-pastel-mint">"User: $($User.DisplayName)" -ForegroundColor Cyan
25 Write-Host class="text-pastel-mint">"TAP: $($TAP.TemporaryAccessPass)" -ForegroundColor Yellow
26 Write-Host class="text-pastel-mint">"Valid for: $LifetimeInMinutes minutes" -ForegroundColor White
27 Write-Host class="text-pastel-mint">"One-time use: $($OneTimeUse.IsPresent)" -ForegroundColor White
28 Write-Host class="text-pastel-mint">"Start Time: $($TAP.StartDateTime)" -ForegroundColor White
29
30 return $TAP
31 } catch {
32 Write-Host class="text-pastel-mint">"Error: $($_.Exception.Message)" -ForegroundColor Red
33 }
34}
35
36class=class="text-pastel-mint">"text-foreground/50 italic"># Example usage
37class=class="text-pastel-mint">"text-foreground/50 italic"># New-TemporaryAccessPass -UserPrincipalName class="text-pastel-mint">"user@domain.com" -LifetimeInMinutes 480 -OneTimeUse
38
39Write-Host class="text-pastel-mint">"Use New-TemporaryAccessPass function to create TAPs" -ForegroundColor Cyan
40Write-Host class="text-pastel-mint">"Example: New-TemporaryAccessPass -UserPrincipalName 'user@domain.comclass="text-pastel-mint">' -LifetimeInMinutes 60" -ForegroundColor Yellow
Click the buttons above to copy or download

Generate Compliance Audit Report

Comprehensive compliance report for auditing and governance

Advanced
ComplianceScript #51
export-compliance-report.ps1powershell
1class=class="text-pastel-mint">"text-foreground/50 italic"># Generate comprehensive compliance report
2Connect-MgGraph -Scopes class="text-pastel-mint">"User.Read.All", class="text-pastel-mint">"Group.Read.All", class="text-pastel-mint">"RoleManagement.Read.All", class="text-pastel-mint">"AuditLog.Read.All"
3
4$ReportDate = Get-Date -Format class="text-pastel-mint">"yyyyMMdd_HHmmss"
5$OutputPath = class="text-pastel-mint">"C:\ComplianceReports\Compliance_$ReportDate"
6New-Item -ItemType Directory -Path $OutputPath -Force | Out-Null
7
8Write-Host class="text-pastel-mint">"Generating Comprehensive Compliance Report..." -ForegroundColor Cyan
9
10class=class="text-pastel-mint">"text-foreground/50 italic"># 1. User Account Status
11Write-Host class="text-pastel-mint">"[1/6] Collecting user data..." -ForegroundColor Yellow
12$Users = Get-MgUser -All -Property DisplayName, UserPrincipalName, AccountEnabled, CreatedDateTime, SignInActivity
13$Users | Export-Csv -Path class="text-pastel-mint">"$OutputPath\Users.csv" -NoTypeInformation
14
15class=class="text-pastel-mint">"text-foreground/50 italic"># 2. Admin Role Assignments
16Write-Host class="text-pastel-mint">"[2/6] Collecting admin roles..." -ForegroundColor Yellow
17$AdminRoles = Get-MgDirectoryRole | Where-Object { $_.DisplayName -like class="text-pastel-mint">"*Admin*" }
18$AdminReport = foreach ($Role in $AdminRoles) {
19 $Members = Get-MgDirectoryRoleMember -DirectoryRoleId $Role.Id
20 foreach ($Member in $Members) {
21 [PSCustomObject]@{
22 Role = $Role.DisplayName
23 Member = $Member.AdditionalProperties.displayName
24 MemberUPN = $Member.AdditionalProperties.userPrincipalName
25 }
26 }
27}
28$AdminReport | Export-Csv -Path class="text-pastel-mint">"$OutputPath\AdminRoles.csv" -NoTypeInformation
29
30class=class="text-pastel-mint">"text-foreground/50 italic"># 3. Guest Users
31Write-Host class="text-pastel-mint">"[3/6] Collecting guest users..." -ForegroundColor Yellow
32$Guests = Get-MgUser -Filter class="text-pastel-mint">"userType eq 'Guestclass="text-pastel-mint">'" -All
33$Guests | Export-Csv -Path class="text-pastel-mint">"$OutputPath\GuestUsers.csv" -NoTypeInformation
34
35class=class="text-pastel-mint">"text-foreground/50 italic"># 4. Inactive Accounts
36Write-Host class="text-pastel-mint">"[4/6] Identifying inactive accounts..." -ForegroundColor Yellow
37$InactiveDate = (Get-Date).AddDays(-90)
38$Inactive = $Users | Where-Object { $_.SignInActivity.LastSignInDateTime -lt $InactiveDate }
39$Inactive | Export-Csv -Path class="text-pastel-mint">"$OutputPath\InactiveUsers.csv" -NoTypeInformation
40
41class=class="text-pastel-mint">"text-foreground/50 italic"># 5. License Usage
42Write-Host class="text-pastel-mint">"[5/6] Collecting license data..." -ForegroundColor Yellow
43$Licenses = Get-MgSubscribedSku
44$Licenses | Select-Object SkuPartNumber, ConsumedUnits, @{N=class="text-pastel-mint">'Available';E={$_.PrepaidUnits.Enabled - $_.ConsumedUnits}} | Export-Csv -Path class="text-pastel-mint">"$OutputPath\Licenses.csv" -NoTypeInformation
45
46class=class="text-pastel-mint">"text-foreground/50 italic"># 6. Security Groups
47Write-Host class="text-pastel-mint">"[6/6] Collecting security groups..." -ForegroundColor Yellow
48$Groups = Get-MgGroup -Filter class="text-pastel-mint">"securityEnabled eq true" -All
49$Groups | Export-Csv -Path class="text-pastel-mint">"$OutputPath\SecurityGroups.csv" -NoTypeInformation
50
51class=class="text-pastel-mint">"text-foreground/50 italic"># Summary
52Write-Host class="text-pastel-mint">"`nCompliance Report Summary:" -ForegroundColor Green
53Write-Host class="text-pastel-mint">"Total Users: $($Users.Count)" -ForegroundColor White
54Write-Host class="text-pastel-mint">"Guest Users: $($Guests.Count)" -ForegroundColor White
55Write-Host class="text-pastel-mint">"Inactive Users: $($Inactive.Count)" -ForegroundColor Yellow
56Write-Host class="text-pastel-mint">"Admin Assignments: $($AdminReport.Count)" -ForegroundColor White
57Write-Host class="text-pastel-mint">"Security Groups: $($Groups.Count)" -ForegroundColor White
58Write-Host class="text-pastel-mint">"`nReports saved to: $OutputPath" -ForegroundColor Cyan
Click the buttons above to copy or download

Configure Identity Governance Settings

Set up access reviews and entitlement management

Advanced
IAMScript #52
manage-identity-governance.ps1powershell
1class=class="text-pastel-mint">"text-foreground/50 italic"># Configure Identity Governance settings
2Connect-MgGraph -Scopes class="text-pastel-mint">"AccessReview.ReadWrite.All", class="text-pastel-mint">"EntitlementManagement.ReadWrite.All"
3
4Write-Host class="text-pastel-mint">"Identity Governance Configuration" -ForegroundColor Cyan
5
6class=class="text-pastel-mint">"text-foreground/50 italic"># Check for access review capability
7try {
8 Write-Host class="text-pastel-mint">"`nAccess Review Settings:" -ForegroundColor Yellow
9
10 class=class="text-pastel-mint">"text-foreground/50 italic"># Note: Access reviews require Azure AD Premium P2
11 Write-Host class="text-pastel-mint">"To create an access review:" -ForegroundColor White
12 Write-Host class="text-pastel-mint">"1. Define scope (group, application, or role)" -ForegroundColor White
13 Write-Host class="text-pastel-mint">"2. Set review frequency (one-time, weekly, monthly, quarterly)" -ForegroundColor White
14 Write-Host class="text-pastel-mint">"3. Assign reviewers (members, owners, or managers)" -ForegroundColor White
15 Write-Host class="text-pastel-mint">"4. Configure auto-apply results" -ForegroundColor White
16
17 Write-Host class="text-pastel-mint">"`nEntitlement Management:" -ForegroundColor Yellow
18 Write-Host class="text-pastel-mint">"Create access packages to bundle resources" -ForegroundColor White
19 Write-Host class="text-pastel-mint">"Define policies for who can request access" -ForegroundColor White
20 Write-Host class="text-pastel-mint">"Set approval workflows" -ForegroundColor White
21 Write-Host class="text-pastel-mint">"Configure automatic assignment and expiration" -ForegroundColor White
22
23 Write-Host class="text-pastel-mint">"`nBest Practices:" -ForegroundColor Green
24 Write-Host class="text-pastel-mint">"- Review admin roles quarterly" -ForegroundColor White
25 Write-Host class="text-pastel-mint">"- Review guest access monthly" -ForegroundColor White
26 Write-Host class="text-pastel-mint">"- Use access packages for temporary access" -ForegroundColor White
27 Write-Host class="text-pastel-mint">"- Enable auto-removal for denied access" -ForegroundColor White
28 Write-Host class="text-pastel-mint">"- Maintain audit logs for compliance" -ForegroundColor White
29
30} catch {
31 Write-Host class="text-pastel-mint">"Error: $($_.Exception.Message)" -ForegroundColor Red
32 Write-Host class="text-pastel-mint">"Note: Identity Governance requires Azure AD Premium P2" -ForegroundColor Yellow
33}
Click the buttons above to copy or download

Monitor Risky Sign-In Detections

Track and report on risky sign-in events from Identity Protection

Advanced
SecurityScript #53
monitor-risky-sign-ins.ps1powershell
1class=class="text-pastel-mint">"text-foreground/50 italic"># Monitor risky sign-in detections
2Connect-MgGraph -Scopes class="text-pastel-mint">"IdentityRiskyUser.Read.All", class="text-pastel-mint">"IdentityRiskEvent.Read.All"
3
4$StartDate = (Get-Date).AddDays(-30)
5
6try {
7 class=class="text-pastel-mint">"text-foreground/50 italic"># Get risky sign-ins
8 $RiskySignIns = Get-MgRiskyUser -All | Where-Object { $_.RiskState -ne class="text-pastel-mint">'none' }
9
10 $Report = foreach ($RiskyUser in $RiskySignIns) {
11 try {
12 $User = Get-MgUser -UserId $RiskyUser.Id -Property DisplayName, UserPrincipalName, Department
13
14 [PSCustomObject]@{
15 UserName = $User.DisplayName
16 UserPrincipalName = $User.UserPrincipalName
17 Department = $User.Department
18 RiskLevel = $RiskyUser.RiskLevel
19 RiskState = $RiskyUser.RiskState
20 RiskDetail = $RiskyUser.RiskDetail
21 LastUpdated = $RiskyUser.RiskLastUpdatedDateTime
22 }
23 } catch {
24 Write-Host class="text-pastel-mint">"Error processing user: $($RiskyUser.Id)" -ForegroundColor Yellow
25 }
26 }
27
28 class=class="text-pastel-mint">"text-foreground/50 italic"># Categorize by risk level
29 $HighRisk = ($Report | Where-Object RiskLevel -eq class="text-pastel-mint">'high').Count
30 $MediumRisk = ($Report | Where-Object RiskLevel -eq class="text-pastel-mint">'medium').Count
31 $LowRisk = ($Report | Where-Object RiskLevel -eq class="text-pastel-mint">'low').Count
32
33 Write-Host class="text-pastel-mint">"Risky Sign-In Report" -ForegroundColor Cyan
34 Write-Host class="text-pastel-mint">"High Risk: $HighRisk" -ForegroundColor Red
35 Write-Host class="text-pastel-mint">"Medium Risk: $MediumRisk" -ForegroundColor Yellow
36 Write-Host class="text-pastel-mint">"Low Risk: $LowRisk" -ForegroundColor Green
37
38 $Report | Sort-Object RiskLevel -Descending | Export-Csv -Path class="text-pastel-mint">"RiskySignIns_$(Get-Date -Format 'yyyyMMddclass="text-pastel-mint">').csv" -NoTypeInformation
39 $Report | Format-Table -AutoSize
40
41} catch {
42 Write-Host class="text-pastel-mint">"Error: $($_.Exception.Message)" -ForegroundColor Red
43 Write-Host class="text-pastel-mint">"Note: Risk detection requires Azure AD Premium P2" -ForegroundColor Yellow
44}
Click the buttons above to copy or download

Configure Security Defaults Settings

Enable or disable security defaults for baseline protection

Intermediate
SecurityScript #54
configure-security-defaults.ps1powershell
1class=class="text-pastel-mint">"text-foreground/50 italic"># Configure Security Defaults
2Connect-MgGraph -Scopes class="text-pastel-mint">"Policy.ReadWrite.ConditionalAccess", class="text-pastel-mint">"Policy.Read.All"
3
4try {
5 class=class="text-pastel-mint">"text-foreground/50 italic"># Get current security defaults status
6 $SecurityDefaults = Get-MgPolicyIdentitySecurityDefaultEnforcementPolicy
7
8 Write-Host class="text-pastel-mint">"Security Defaults Configuration" -ForegroundColor Cyan
9 Write-Host class="text-pastel-mint">"Current Status: $($SecurityDefaults.IsEnabled)" -ForegroundColor $(if($SecurityDefaults.IsEnabled){class="text-pastel-mint">'Green'}else{class="text-pastel-mint">'Yellow'})
10
11 Write-Host class="text-pastel-mint">"`nSecurity Defaults Include:" -ForegroundColor Yellow
12 Write-Host class="text-pastel-mint">"- Require MFA for administrators" -ForegroundColor White
13 Write-Host class="text-pastel-mint">"- Require MFA for users when necessary" -ForegroundColor White
14 Write-Host class="text-pastel-mint">"- Block legacy authentication protocols" -ForegroundColor White
15 Write-Host class="text-pastel-mint">"- Protect privileged activities (Azure Portal access)" -ForegroundColor White
16 Write-Host class="text-pastel-mint">"- Require users to register for MFA" -ForegroundColor White
17
18 class=class="text-pastel-mint">"text-foreground/50 italic"># To enable security defaults
19 class=class="text-pastel-mint">"text-foreground/50 italic"># Update-MgPolicyIdentitySecurityDefaultEnforcementPolicy -IsEnabled $true
20
21 class=class="text-pastel-mint">"text-foreground/50 italic"># To disable security defaults (needed for Conditional Access)
22 class=class="text-pastel-mint">"text-foreground/50 italic"># Update-MgPolicyIdentitySecurityDefaultEnforcementPolicy -IsEnabled $false
23
24 Write-Host class="text-pastel-mint">"`nNote: Security Defaults and Conditional Access are mutually exclusive" -ForegroundColor Yellow
25 Write-Host class="text-pastel-mint">"Disable Security Defaults before implementing CA policies" -ForegroundColor Yellow
26
27} catch {
28 Write-Host class="text-pastel-mint">"Error: $($_.Exception.Message)" -ForegroundColor Red
29}
Click the buttons above to copy or download

Export Application Role Assignments

Report on app role assignments for enterprise applications

Advanced
IAMScript #55
export-app-role-assignments.ps1powershell
1class=class="text-pastel-mint">"text-foreground/50 italic"># Export application role assignments
2Connect-MgGraph -Scopes class="text-pastel-mint">"Application.Read.All", class="text-pastel-mint">"Directory.Read.All"
3
4$ServicePrincipals = Get-MgServicePrincipal -All
5$Report = @()
6
7Write-Host class="text-pastel-mint">"Processing $($ServicePrincipals.Count) service principals..." -ForegroundColor Cyan
8
9foreach ($SP in $ServicePrincipals) {
10 try {
11 $AppRoleAssignments = Get-MgServicePrincipalAppRoleAssignedTo -ServicePrincipalId $SP.Id -All
12
13 foreach ($Assignment in $AppRoleAssignments) {
14 try {
15 $Principal = Get-MgDirectoryObject -DirectoryObjectId $Assignment.PrincipalId
16
17 class=class="text-pastel-mint">"text-foreground/50 italic"># Get app role details
18 $AppRole = $SP.AppRoles | Where-Object { $_.Id -eq $Assignment.AppRoleId }
19
20 $Report += [PSCustomObject]@{
21 ApplicationName = $SP.DisplayName
22 ApplicationId = $SP.AppId
23 PrincipalName = $Principal.AdditionalProperties.displayName
24 PrincipalType = $Principal.AdditionalProperties.class="text-pastel-mint">'@odata.type' -replace class="text-pastel-mint">'class="text-foreground/50 italicclass="text-pastel-mint">">#microsoft.graph.', class="text-pastel-mint">''
25 PrincipalId = $Assignment.PrincipalId
26 RoleName = if ($AppRole) { $AppRole.DisplayName } else { class="text-pastel-mint">"Default" }
27 RoleDescription = if ($AppRole) { $AppRole.Description } else { class="text-pastel-mint">"Default Access" }
28 AssignedDate = $Assignment.CreatedDateTime
29 }
30 } catch {
31 Write-Host class="text-pastel-mint">"Error processing assignment for $($SP.DisplayName)" -ForegroundColor Yellow
32 }
33 }
34 } catch {
35 class=class="text-pastel-mint">"text-foreground/50 italic"># Skip if no assignments
36 }
37}
38
39Write-Host class="text-pastel-mint">"Total app role assignments: $($Report.Count)" -ForegroundColor Green
40$Report | Export-Csv -Path class="text-pastel-mint">"AppRoleAssignments_$(Get-Date -Format 'yyyyMMddclass="text-pastel-mint">').csv" -NoTypeInformation
41$Report | Format-Table ApplicationName, PrincipalName, RoleName -AutoSize
Click the buttons above to copy or download

Manage User Profile Photos

Bulk upload or export user profile photos

Intermediate
Entra ID ManagementScript #56
manage-user-photos.ps1powershell
1class=class="text-pastel-mint">"text-foreground/50 italic"># Manage user profile photos
2Connect-MgGraph -Scopes class="text-pastel-mint">"User.ReadWrite.All"
3
4function Set-UserProfilePhoto {
5 param(
6 [Parameter(Mandatory=$true)]
7 [string]$UserPrincipalName,
8 [Parameter(Mandatory=$true)]
9 [string]$PhotoPath
10 )
11
12 try {
13 $User = Get-MgUser -Filter class="text-pastel-mint">"userPrincipalName eq '$UserPrincipalNameclass="text-pastel-mint">'"
14
15 if (Test-Path $PhotoPath) {
16 $PhotoBytes = [System.IO.File]::ReadAllBytes($PhotoPath)
17 Set-MgUserPhotoContent -UserId $User.Id -InFile $PhotoPath
18
19 Write-Host class="text-pastel-mint">"Photo updated for: $($User.DisplayName)" -ForegroundColor Green
20 } else {
21 Write-Host class="text-pastel-mint">"Photo file not found: $PhotoPath" -ForegroundColor Red
22 }
23 } catch {
24 Write-Host class="text-pastel-mint">"Error: $($_.Exception.Message)" -ForegroundColor Red
25 }
26}
27
28function Export-UserProfilePhoto {
29 param(
30 [Parameter(Mandatory=$true)]
31 [string]$UserPrincipalName,
32 [Parameter(Mandatory=$true)]
33 [string]$OutputPath
34 )
35
36 try {
37 $User = Get-MgUser -Filter class="text-pastel-mint">"userPrincipalName eq '$UserPrincipalNameclass="text-pastel-mint">'"
38 Get-MgUserPhotoContent -UserId $User.Id -OutFile $OutputPath
39
40 Write-Host class="text-pastel-mint">"Photo exported for: $($User.DisplayName) to $OutputPath" -ForegroundColor Green
41 } catch {
42 Write-Host class="text-pastel-mint">"No photo found for: $UserPrincipalName" -ForegroundColor Yellow
43 }
44}
45
46class=class="text-pastel-mint">"text-foreground/50 italic"># Example usage:
47Write-Host class="text-pastel-mint">"User Photo Management Functions:" -ForegroundColor Cyan
48Write-Host class="text-pastel-mint">"Set-UserProfilePhoto -UserPrincipalName 'user@domain.comclass="text-pastel-mint">' -PhotoPath 'C:\Photos\user.jpgclass="text-pastel-mint">'" -ForegroundColor Yellow
49Write-Host class="text-pastel-mint">"Export-UserProfilePhoto -UserPrincipalName 'user@domain.comclass="text-pastel-mint">' -OutputPath 'C:\Export\user.jpgclass="text-pastel-mint">'" -ForegroundColor Yellow
Click the buttons above to copy or download

Audit Application Credentials Expiry

Monitor and report on expiring app registration credentials

Intermediate
SecurityScript #57
audit-app-credentials.ps1powershell
1class=class="text-pastel-mint">"text-foreground/50 italic"># Audit application credentials expiry
2Connect-MgGraph -Scopes class="text-pastel-mint">"Application.Read.All"
3
4$Applications = Get-MgApplication -All
5$WarningDays = 30
6$Report = @()
7
8Write-Host class="text-pastel-mint">"Auditing $($Applications.Count) applications..." -ForegroundColor Cyan
9
10foreach ($App in $Applications) {
11 class=class="text-pastel-mint">"text-foreground/50 italic"># Check password credentials (secrets)
12 foreach ($Secret in $App.PasswordCredentials) {
13 $DaysUntilExpiry = ($Secret.EndDateTime - (Get-Date)).Days
14
15 if ($DaysUntilExpiry -le $WarningDays) {
16 $Report += [PSCustomObject]@{
17 ApplicationName = $App.DisplayName
18 ApplicationId = $App.AppId
19 ObjectId = $App.Id
20 CredentialType = class="text-pastel-mint">"Secret"
21 KeyId = $Secret.KeyId
22 DisplayName = $Secret.DisplayName
23 StartDate = $Secret.StartDateTime
24 ExpiryDate = $Secret.EndDateTime
25 DaysUntilExpiry = $DaysUntilExpiry
26 Status = if ($DaysUntilExpiry -lt 0) { class="text-pastel-mint">"Expired" } elseif ($DaysUntilExpiry -le 7) { class="text-pastel-mint">"Critical" } else { class="text-pastel-mint">"Warning" }
27 }
28 }
29 }
30
31 class=class="text-pastel-mint">"text-foreground/50 italic"># Check certificate credentials
32 foreach ($Cert in $App.KeyCredentials) {
33 $DaysUntilExpiry = ($Cert.EndDateTime - (Get-Date)).Days
34
35 if ($DaysUntilExpiry -le $WarningDays) {
36 $Report += [PSCustomObject]@{
37 ApplicationName = $App.DisplayName
38 ApplicationId = $App.AppId
39 ObjectId = $App.Id
40 CredentialType = class="text-pastel-mint">"Certificate"
41 KeyId = $Cert.KeyId
42 DisplayName = $Cert.DisplayName
43 StartDate = $Cert.StartDateTime
44 ExpiryDate = $Cert.EndDateTime
45 DaysUntilExpiry = $DaysUntilExpiry
46 Status = if ($DaysUntilExpiry -lt 0) { class="text-pastel-mint">"Expired" } elseif ($DaysUntilExpiry -le 7) { class="text-pastel-mint">"Critical" } else { class="text-pastel-mint">"Warning" }
47 }
48 }
49 }
50}
51
52$Expired = ($Report | Where-Object Status -eq class="text-pastel-mint">"Expired").Count
53$Critical = ($Report | Where-Object Status -eq class="text-pastel-mint">"Critical").Count
54$Warning = ($Report | Where-Object Status -eq class="text-pastel-mint">"Warning").Count
55
56Write-Host class="text-pastel-mint">"`nApplication Credentials Status:" -ForegroundColor Cyan
57Write-Host class="text-pastel-mint">"Expired: $Expired" -ForegroundColor Red
58Write-Host class="text-pastel-mint">"Critical (<7 days): $Critical" -ForegroundColor Yellow
59Write-Host class="text-pastel-mint">"Warning (<30 days): $Warning" -ForegroundColor Yellow
60
61$Report | Sort-Object DaysUntilExpiry | Export-Csv -Path class="text-pastel-mint">"AppCredentialsExpiry_$(Get-Date -Format 'yyyyMMddclass="text-pastel-mint">').csv" -NoTypeInformation
62$Report | Format-Table ApplicationName, CredentialType, DaysUntilExpiry, Status -AutoSize
Click the buttons above to copy or download

Have a script to share?

We're always looking for community contributions. Submit your PowerShell scripts and help other administrators automate their workflows.

Submit Your Script