Overview
This procedure outlines the steps to import guest users into Microsoft Entra ID (formerly Azure AD) using a PowerShell script that leverages the Microsoft Graph API.
Unlike the standard guest invitation process, this script enhances user profiles by automatically setting additional attributes, such as:
- Mobile Phone
- Company Name
- Usage Location (defaults to Belgium)
Key Benefits of this Automated Process
- Saves time – No manual user entry required.
- Ensures consistency – Standardized name formatting (DUPONT Jean-Claude).
- Enhances guest user management – Additional attributes ensure proper user records.
- Avoids duplicate users – The script checks if a user exists before adding them.
Prerequisites
1. Install Microsoft Graph PowerShell SDK
If not installed, open PowerShell as Administrator and run:
Install-Module Microsoft.Graph -Scope AllUsers -Force
This ensures access to the Microsoft Graph API commands.
2. Set PowerShell Execution Policy
Allow script execution for the current session:
Set-ExecutionPolicy RemoteSigned -Scope Process
This prevents security restrictions from blocking the script.
3. Required Permissions in Azure AD
Ensure your Azure AD account has the following permissions:
- User.Invite.All → To invite guest users.
- User.ReadWrite.All → To update user properties (e.g., phone, company, location).
You can check your permissions in the Microsoft Entra Admin Center.
CSV File Structure (Including Additional Attributes)
The script reads a CSV file containing user information. Ensure it follows this format:
FirstName | LastName | MobilePhone | Company | |
---|---|---|---|---|
John | Dupont | john.dupont@example.com | +33612345678 | Example Corp |
Jane | Smith | jane.smith@example.com | +447987654321 | Tech Solutions |
Alice | Johnson | alice.johnson@example.com | +491579876543 | Innovate Ltd |
Bob | Brown | bob.brown@example.com | Softworks Inc. | |
Charlie | Davis | charlie.davis@example.com | +11234567890 | FutureTech |
Example CSV file:
FirstName,LastName,Email,MobilePhone,Company John,Dupont, john.dupont@example.com,+33612345678,Example Corp Jane,Smith, jane.smith@example.com,+447987654321,Tech Solutions Alice,Johnson, alice.johnson@example.com,+491579876543,Innovate Ltd Bob,Brown, bob.brown@example.com,Softworks Inc. Charlie,Davis, charlie.davis@example.com,+11234567890,FutureTech
Notes:
- LastName → Will be automatically converted to UPPERCASE.
- FirstName → Will be formatted correctly, preserving hyphens (Jean-Claude).
- MobilePhone → Optional but will be added if available.
- Company → Optional but will be added if provided.
You can also add other attributes if you have more requirements, but think to also adapt the script in this case.
Save the file as:
C:\Scripts\GuestsImport.csv
The script
# Import Microsoft Graph module # Import-Module Microsoft.Graph ####################### CONFIGURATION SECTION ####################### # Define the path to the CSV file $csvFilePath = "C:\Scripts\GuestsImport.csv" # Microsoft Graph API permissions required: "User.Invite.All", "User.ReadWrite.All" $scopes = "User.Invite.All", "User.ReadWrite.All" ####################### FUNCTION TO FORMAT FIRST NAME ####################### function Format-FirstName($firstName) { if (-not $firstName) { return $null } # Return null if empty # Process each name part separately while preserving hyphens $formattedParts = $firstName -split " " | ForEach-Object { ($_.Split("-") | ForEach-Object { if ($_.Length -gt 1) { $_.Substring(0,1).ToUpper() + $_.Substring(1).ToLower() } else { $_.ToUpper() } }) -join "-" } return $formattedParts -join " " } ####################### CONNECT TO MICROSOFT GRAPH (INTERACTIVE LOGIN) ####################### Write-Host "Connecting to Microsoft Graph... Please enter your credentials." -ForegroundColor Cyan try { Connect-MgGraph -Scopes $scopes -ErrorAction Stop } catch { Write-Host "Failed to authenticate to Microsoft Graph. Please check your credentials." -ForegroundColor Red return } # Ensure that the connection is valid before proceeding if (-not (Get-MgContext)) { Write-Host "Microsoft Graph connection is not active. Exiting script." -ForegroundColor Red return } ####################### CHECK CSV FILE ####################### if (-Not (Test-Path $csvFilePath)) { Write-Host "CSV file not found at $csvFilePath. Please check the path." -ForegroundColor Red return } # Import the CSV file $guestUsers = Import-Csv -Path $csvFilePath # Ensure the file contains users if ($guestUsers.Count -eq 0) { Write-Host "No users found in the CSV file. Exiting script." -ForegroundColor Yellow return } ####################### PROCESSING USERS ####################### foreach ($user in $guestUsers) { $formattedLastName = $user.LastName.ToUpper() # Convert last name to uppercase $formattedFirstName = Format-FirstName $user.FirstName # Properly format first name $displayName = "$formattedLastName $formattedFirstName" # Format as LASTNAME Firstname $email = $user.Email $mobilePhone = $user.MobilePhone $company = $user.Company # Check if the user already exists in Entra ID (Azure AD) $existingUser = Get-MgUser -Filter "mail eq '$email'" -ErrorAction SilentlyContinue if ($existingUser) { Write-Host "User $email already exists." -ForegroundColor Yellow continue } # Define guest user invitation properties $newGuestUser = @{ invitedUserDisplayName = $displayName invitedUserEmailAddress = $email invitedUserType = "Guest" sendInvitationMessage = $false # No email will be sent inviteRedirectUrl = "https://myapps.microsoft.com" # Default landing page for guests invitedUserMessageInfo = @{ customizedMessageBody = "You have been added as a guest user." } } # Create the guest user in Azure AD (Entra ID) try { $invitation = New-MgInvitation -BodyParameter $newGuestUser -ErrorAction Stop $guestUserId = $invitation.InvitedUser.Id # Get the new user's ID Write-Host "Guest user invited: $displayName ($email)" -ForegroundColor Green # Prepare update properties (only update if fields exist) $updateProperties = @{} $updateProperties["givenName"] = $formattedFirstName $updateProperties["surname"] = $formattedLastName $updateProperties["usageLocation"] = "BE" # Set default location to Belgium if ($mobilePhone) { $updateProperties["mobilePhone"] = $mobilePhone } if ($company) { $updateProperties["companyName"] = $company } # Update the guest user with additional details if ($updateProperties.Count -gt 0) { Update-MgUser -UserId $guestUserId -BodyParameter $updateProperties Write-Host "Updated guest user details for: $displayName ($email)" -ForegroundColor Cyan } } catch { Write-Host "Error inviting/updating $email : $_" -ForegroundColor Red } } Write-Host "Guest import process completed!" -ForegroundColor Cyan ####################### DISCONNECT FROM MICROSOFT GRAPH ####################### Disconnect-MgGraph Write-Host "Disconnected from Microsoft Graph." -ForegroundColor Magenta
Running the Script
1. Open PowerShell and navigate to the script location:
cd C:\Scripts\
2. Run the script:
.\GuestsImportScript.ps1
3. Authenticate to Microsoft Graph when prompted.
- A sign-in window will appear.
- Use an account with User.Invite.All and User.ReadWrite.All permissions.
The script will automatically:
- Check if each guest user already exists.
- Invite new users without sending an email invitation.
- Apply correct name formatting (e.g., "DUPONT Jean-Claude").
- Add additional attributes (MobilePhone, Company, Usage Location).
Expected Output
During execution, PowerShell will display messages indicating the progress:
- Guest user invited: DUPONT Jean-Claude (jean.claude@example.com)
- Updated guest user details (MobilePhone, Company, Usage Location)
- User alice.johnson@example.com already exists. (Skipped)
- Error inviting/updating user: user@example.com (If something fails)
After the script completes, all new guest users will be added to Microsoft Entra ID with enriched profile details.
Verifying Imported Users
1. Go to Microsoft Entra Admin Center
2. Check the guest users list
- Navigate to Users > External Identities
- Filter by Guest users
3. Verify user details
- Click on a guest user to check:
- First Name & Last Name (Correct format)
- Mobile Phone (If available)
- Company Name (If provided)
- Usage Location (Set to Belgium)
Troubleshooting
1. Error: "Could not load file or assembly 'Microsoft.Graph.Authentication'"
Solution: Reinstall the Microsoft Graph module:
Uninstall-Module Microsoft.Graph -AllVersions -Force Install-Module Microsoft.Graph -Scope AllUsers -Force
Restart PowerShell and try again.
2. Error: "PipelineStoppedException: The pipeline has been stopped."
Solution: Likely due to authentication failure. Ensure your account has the required permissions.
3. Error: "CSV file not found."
Solution: Verify that the CSV file exists at the specified path:
C:\Scripts\GuestsImport.csv
Conclusion
This script streamlines guest user onboarding in Microsoft Entra ID, ensuring:
- Consistent formatting of names.
- Automatic assignment of additional attributes (phone, company, location).
- Duplicate prevention by checking existing users.