Get-MgUser – a reliable way to retrieve User Details

In this post, we’ll walk through a PowerShell script that leverages Microsoft Graph and Get-MgUser cmdlet to retrieve essential user details, such as display name, email, job title, and more, directly from Entra ID. This simple yet powerful script can be a valuable tool for administrators looking to automate user information retrieval.

Get-MgUser Cmdlet

The Get-MgUser cmdlet is a key component of the Microsoft Graph PowerShell SDK, allowing administrators to interact with user data in Microsoft Entra ID. This cmdlet provides a straightforward way to retrieve information about users in your organization. It can be used to fetch details such as user names, email addresses, job titles, departments, and more, based on various filters or criteria.

One of the primary benefits of Get-MgUser is its integration with Microsoft Graph, enabling access to a wealth of data stored in Entra ID. For instance, you can use the -Filter parameter to search for specific users by their User Principal Name (UPN) or other attributes. In addition to basic user information, Get-MgUser can also retrieve properties related to the user’s account status, such as whether their account is enabled or not.

With its versatility and ease of use, Get-MgUser is an indispensable tool for administrators working with Microsoft Graph to automate user management tasks, whether it’s for generating reports, troubleshooting, or integrating with other systems.

Understanding the PowerShell Script

In this section, we’ll break down the PowerShell script used to retrieve user details from Microsoft Entra ID. The script begins by importing the Microsoft Graph module, which is necessary for interacting with Entra ID data. It then establishes a connection to Microsoft Graph using the Connect-MgGraph cmdlet with the “User.Read.All” scope, ensuring the necessary permissions are granted for reading user data.

The core of the script is the Get-EntraUserDetails function, which accepts a User Principal Name (UPN) as a parameter. It uses the Get-MgUser cmdlet with a filter to retrieve user information based on the provided UPN. If the user exists, their details—such as display name, job title, department, and account status—are returned in a structured object. If the user is not found or an error occurs, the function returns an object indicating the issue.

The script also handles input and output files. It reads UPNs from a text file (userUPNs.txt) and processes each one individually, collecting results in an array. Finally, it exports the retrieved user details to a CSV file (UserDetails.csv), making it easy to review and use the data in other applications or reports.

You can find the code in my GitHub Page.

In case you need to find all available returned fields of a cmdlet and specifically of the Get-MgUser cmdlet, check the following post. In case you want to add more fields, just find the field name and add it in the script below.

# Import the Microsoft Graph module - if required
# Import-Module Microsoft.Graph

# Connect to Microsoft Graph
Connect-MgGraph -Scopes "User.Read.All"

# Function to get user details by UPN
function Get-EntraUserDetails {
    param (
        [Parameter(Mandatory = $true)]
        [string]$UserPrincipalName
    )

    try {
        # Retrieve the user details from Microsoft Entra ID (Azure AD)
        $user = Get-MgUser -Filter "userPrincipalName eq '$UserPrincipalName'"
        
        if ($user) {
            # Return the user details as an object
            return [PSCustomObject]@{
                DisplayName      = $user.DisplayName
                UserPrincipalName = $user.UserPrincipalName
                Mail             = $user.Mail
                JobTitle         = $user.JobTitle
                Department       = $user.Department
                MobilePhone      = $user.MobilePhone
                AccountEnabled   = $user.AccountEnabled
                Status           = "Found"
            }
        } else {
            # Return an object indicating the user was not found
            return [PSCustomObject]@{
                DisplayName      = ""
                UserPrincipalName = $UserPrincipalName
                Mail             = ""
                JobTitle         = ""
                Department       = ""
                MobilePhone      = ""
                AccountEnabled   = ""
                Status           = "Not Found"
            }
        }
    } catch {
        # Handle errors and return an object indicating the error
        return [PSCustomObject]@{
            DisplayName      = ""
            UserPrincipalName = $UserPrincipalName
            Mail             = ""
            JobTitle         = ""
            Department       = ""
            MobilePhone      = ""
            AccountEnabled   = ""
            Status           = "Error: $_"
        }
    }
}

# Define the input and output file paths
$inputFile = "C:\Temp\userUPNs.txt"  # Path to the input text file containing UPNs
$outputFile = "C:\Temp\UserDetails.csv"  # Path to the output CSV file

# Check if the input file exists
if (-Not (Test-Path $inputFile)) {
    Write-Host "Input file '$inputFile' not found. Please provide a valid file path." -ForegroundColor Red
    exit
}

# Read UPNs from the input file
$userUPNs = Get-Content -Path $inputFile

# Initialize an array to store the results
$resultList = @()

# Loop through each UPN and get user details
foreach ($upn in $userUPNs) {
    Write-Host "Processing UPN: $upn" -ForegroundColor Yellow
    $result = Get-EntraUserDetails -UserPrincipalName $upn
    $resultList += $result

    # Print each user record to the screen
    Write-Host "User Details for $upn :"
    Write-Host "Display Name: $($result.DisplayName)"
    Write-Host "UPN: $($result.UserPrincipalName)"
    Write-Host "Mail: $($result.Mail)"
    Write-Host "Job Title: $($result.JobTitle)"
    Write-Host "Department: $($result.Department)"
    Write-Host "Mobile Phone: $($result.MobilePhone)"
    Write-Host "Account Enabled: $($result.AccountEnabled)"
    Write-Host "Status: $($result.Status)"
    Write-Host "----------------------------------------"
}

# Export the results to a CSV file
$resultList | Export-Csv -Path $outputFile -NoTypeInformation -Encoding UTF8

Write-Host "User details have been exported to '$outputFile'." -ForegroundColor Green

Important Note on the Get-MgUser Cmdlet

The -Filter parameter in the Get-MgUser cmdlet has some limitations when it comes to filtering by certain fields. For instance, if your environment has on-premises synchronization enabled and you attempt to use the OnPremisesSamAccountName field with the -Filter parameter, you may encounter an error. This is due to the fact that not all fields are supported by the -Filter parameter for direct querying.

To work around this limitation, one solution is to retrieve all users using the -All parameter, and then apply additional filtering using the Where-Object cmdlet. For example, you can retrieve all users and filter by OnPremisesSamAccountName like this:

Get-MgUser -All | Where-Object { $_.OnPremisesSamAccountName -eq "somevalue" }

This approach allows you to bypass the filtering restrictions and retrieve the data you need.

References – Documentation

Other Interesting Posts

Leave a Reply

Your email address will not be published. Required fields are marked *