Managing user accounts in Microsoft 365 can be a challenging task, especially when it comes to tracking new user additions. In this article, we'll provide a PowerShell script that retrieves all Microsoft 365 users created within the last month. This script utilizes the Microsoft Graph PowerShell module and can be a valuable tool for administrators to monitor new user accounts.
Here is the PowerShell script to fetch Microsoft 365 users created within the last month:
# Ensure the Microsoft.Graph module is installed and imported
Install-Module -Name Microsoft.Graph -Force -AllowClobber
Import-Module Microsoft.Graph
# Connect to Microsoft Graph
Connect-MgGraph -Scopes "User.Read.All"
# Calculate the date 30 days ago from today
$DateThreshold = (Get-Date).AddDays(-30)
# Fetch all users
$AllUsers = Get-MgUser -All -Property DisplayName, UserPrincipalName, CreatedDateTime
# Filter users created within the last 30 days
$RecentUsers = $AllUsers | Where-Object { [datetime]$_.CreatedDateTime -ge $DateThreshold }
# Display the results
$RecentUsers | Select-Object DisplayName, UserPrincipalName, CreatedDateTime
Script Output
The script begins by ensuring that the Microsoft.Graph module is installed and imported for use. This module allows us to interact with Microsoft Graph API through PowerShell.
The Connect-MgGraph cmdlet is used to authenticate and establish a connection to the Microsoft Graph API. You will be prompted to provide your credentials.
The script calculates the date 30 days ago from the current date using Get-Date and AddDays(-30). This date is used as the threshold to filter users created within the last 30 days.
The Get-MgUser cmdlet fetches all users from Microsoft 365, including their display names, user principal names, and creation dates.
Using Where-Object, the script filters the users based on their CreatedDateTime property to include only those created within the last 30 days.
The script then selects and displays the relevant properties (DisplayName, UserPrincipalName, CreatedDateTime) of the filtered users.
Get-MgUser : Unsupported or invalid query filter clause specified for property 'createdDateTime' of resource 'User'.
Status: 400 (BadRequest)
ErrorCode: Request_UnsupportedQuery
Solution:
Connect-MgGraph : Exception of type 'Microsoft.Graph.Auth.AuthException' was thrown.
Solution:
Too many requests error.
Solution:
Using the Microsoft Graph PowerShell module, administrators can efficiently retrieve and monitor new user accounts created within the last month in Microsoft 365. This script provides a straightforward solution to track user additions, ensuring compliance and security within your organization. By understanding the script's components, use cases, and potential errors, you can effectively integrate this tool into your administrative toolkit.
© m365corner.com. All Rights Reserved. Design by HTML Codex