Forum Discussion
Facing error when running a ps script using mggraph
- Aug 29, 2024
Hi.
Your second and third Invoke-RestMethod URIs don't look properly formatted to me, going off what you've pasted in this thread.
Because the strings are using double-quotes, PowerShell will parse breakout characters like $ and ? instead of interpreting them literally.
I haven't bothered running a real test as there's no need. In the examples below, the only thing we're interested in is the parsed URI in yellow. Here, you can see that based on your code, you're not going to get the URI you think you're getting (first example) unless you remember to escape the special characters (second example).
Cheers,
Lain
You've outlined two issues, so I'll go through them in turn.
Could not retrieve userId for ''
This is simply a problem with the script. You'll have to debug your own way through this as without an actual error referencing the line causing the issue, I have nothing to work with.
userPrincipalName is not a mandatory field for Active Directory, either, so one possibility is that you have retrieved an account that has no value set for userPrincipalName. (As is the by-default case for the built-in Administrator account.)
Fetching more than 100 users at a time
Have a read of the following articles as you will need to make use of paging.
- Paging Microsoft Graph data in your app - Microsoft Graph | Microsoft Learn
- Use the Microsoft Search API to query data - Microsoft Graph v1.0 | Microsoft Learn
100 users is the default page size; 999 is the maximum and a "reasonable" figure to use is 200.
In the following simplistic example, I've used a page size of two ($top=2), which as you can see from the iteration means that the loop has executed seven times to retrieve all users.
Example paging script
$iteration = 0;
$uri = "https://graph.microsoft.com/beta/users?`$top=2&`$select=id,userPrincipalName";
do {
$Response = Invoke-MgGraphRequest -Method GET -Uri $uri -OutputType PSObject;
$Response.value | ForEach-Object {
[PSCustomObject] @{
iteration = $iteration;
id = $_.id;
}
};
$iteration++;
$uri = $Response.'@odata.nextLink';
} while ($null -ne $uri);
Example paging output
Cheers,
Lain