Mastering the Foibles of the Microsoft Graph PowerShell SDK

He looks happy, but he hasn't hit some of the Microsoft Graph PowerShell SDK foibles yet...
He looks happy, but he hasn’t hit some of the SDK foibles yet…

Translating Graph API Requests to PowerShell Cmdlets Sometimes Doesn’t Go So Well

The longer you work with a technology, the more you come to know about its strengths and weaknesses. I’ve been working with the Microsoft Graph PowerShell SDK for about two years now. I like the way that the SDK makes Graph APIs more accessible to people accustomed to developing PowerShell scripts, but I hate some of the SDK’s foibles.

This article describes the Microsoft Graph PowerShell SDK idiosyncrasies that cause me most heartburn. All are things to look out for when converting scripts from the Azure AD and MSOL modules before their deprecation (speaking of which, here’s an interesting tool that might help with this work).

No Respect for $Null

Sometimes you just don’t want to write something into a property and that’s what PowerShell’s $Null variable is for. But the Microsoft Graph PowerShell SDK cmdlets don’t like it when you use $Null. For example, let’s assume you want to create a new Azure AD user account. This code creates a hash table with the properties of the new account and then runs the New-MgUser cmdlet.

$NewUserProperties = @{
    GivenName = $FirstName
    Surname = $LastName
    DisplayName = $DisplayName
    JobTitle = $JobTitle
    Department = $Null
    MailNickname = $NickName
    Mail = $PrimarySmtpAddress
    UserPrincipalName = $UPN
    Country = $Country
    PasswordProfile = $NewPasswordProfile
    AccountEnabled = $true }
$NewGuestAccount = New-MgUser @NewUserProperties

New-MgUser fails because of an invalid value for the department property, even though $Null is a valid PowerShell value.

New-MgUser : Invalid value specified for property 'department' of resource 'User'.
At line:1 char:2
+  $NewGuestAccount = New-MgUser @NewUserProperties
+  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: ({ body = Micros...oftGraphUser1 }:<>f__AnonymousType64`1) [New-MgUser
   _CreateExpanded], RestException`1
    + FullyQualifiedErrorId : Request_BadRequest,Microsoft.Graph.PowerShell.Cmdlets.NewMgUser_CreateExpanded

One solution is to use a variable that holds a single space. Another is to pass $Null by running the equivalent Graph request using the Invoke-MgGraphRequest cmdlet. Neither are good answers to what should not happen (and we haven’t even mentioned the inability to filter on null values).

Ignoring the Pipeline

The pipeline is a fundamental building block of PowerShell. It allows objects retrieve by a cmdlet to pass to another cmdlet for processing. But despite the usefulness of the pipeline, the SDK cmdlets don’t support it and the pipeline stops stone dead whenever an SDK cmdlet is asked to process incoming objects. For example:

Get-MgUser -Filter "userType eq 'Guest'" -All | Update-MgUser -Department "Guest Accounts"
Update-MgUser : The pipeline has been stopped

Why does this happen? The cmdlet that receives objects must be able to distinguish between the different objects before it can work on them. In this instance, Get-MgUser delivers a set of guest accounts, but the Update-MgUser cmdlet does not know how to process each object because it identifies an object is through the UserId parameter whereas the inbound objects offer an identity in the Id property.

The workaround is to store the set of objects in an array and then process the objects with a ForEach loop.

Property Casing and Fetching Data

I’ve used DisplayName to refer to the display name of objects since I started to use PowerShell with Exchange Server 2007. I never had a problem with uppercasing the D and N in the property name until the Microsoft Graph PowerShell SDK came along only to find that sometimes SDK cmdlets insist on a specific form of casing for property names. Fail to comply, and you don’t get your data.

What’s irritating is that the restriction is inconsistent. For instance, both these commands work:

Get-MgGroup -Filter "DisplayName eq 'Ultra Fans'"
Get-MgGroup -Filter "displayName eq 'Ultra Fans'"

But let’s say that I want to find the group members with the Get-MgGroupMember cmdlet:

[array]$GroupMembers = Get-MgGroupMember -GroupId (Get-MgGroup -Filter "DisplayName eq 'Ultra Fans'" | Select-Object -ExpandProperty Id)

This works, but I end up with a set of identifiers pointing to individual group members. Then I remember from experience gained from building scripts to report group membership that Get-MgGroupMember (like other cmdlets dealing with membership like Get-MgAdministrationUnitMember) returns a property called AdditionalProperties holding extra information about members. So I try:

$GroupMembers.AdditionalProperties.DisplayName

Nope! But if I change the formatting to displayName, I get the member names:

$GroupMembers.AdditionalProperties.displayName
Tony Redmond
Kim Akers
James Ryan
Ben James
John C. Adams
Chris Bishop

Talk about frustrating confusion! It’s not just display names. Reference to any property in AdditionalProperties must use the same casing as used the output, like userPrincipalName and assignedLicenses.

Another example is when looking for sign-in logs. This command works because the format of the user principal name is the same way as stored in the sign-in log data:

[array]$Logs = Get-MgAuditLogSignIn -Filter "UserPrincipalName eq 'james.ryan@office365itpros.com'" -All

Uppercasing part of the user principal name causes the command to return zero hits:

[array]$Logs = Get-MgAuditLogSignIn -Filter "UserPrincipalName eq 'James.Ryan@office365itpros.com'" -All

Two SDK foibles are on show here. First, the way that cmdlets return sets of identifiers and stuff information into AdditionalProperties (something often overlooked by developers who don’t expect this to be the case). Second, the inconsistent insistence by cmdlets on exact matching for property casing.

I’m told that this is all due to the way Graph APIs work. My response is that it’s not beyond the ability of software engineering to hide complexities from end users by ironing out these kinds of issues.

GUIDs and User Principal Names

Object identification for Graph requests depends on globally unique identifiers (GUIDs). Everything has a GUID. Both Graph requests and SDK cmdlets use GUIDs to find information. But some SDK cmdlets can pass user principal names instead of GUIDs when looking for user accounts. For instance, this works:

Get-MgUser -UserId Tony.Redmond@office365itpros.com

Unless you want to include the latest sign-in activity date for the account.

Get-MgUser -UserId Tony.Redmond@office365itpros.com -Property signInActivity
Get-MgUser :
{"@odata.context":"http://reportingservice.activedirectory.windowsazure.com/$metadata#Edm.String","value":"Get By Key
only supports UserId and the key has to be a valid Guid"}

The reason is that the sign-in data comes from a different source which requires a GUID to lookup the sign-in activity for the account, so we must pass the object identifier for the account for the command to work:

Get-MgUser -UserId "eff4cd58-1bb8-4899-94de-795f656b4a18" -Property signInActivity

It’s safer to use GUIDs everywhere. Don’t depend on user principal names because a cmdlet might object – and user principal names can change.

No Fix for Problems in V2 of the Microsoft Graph PowerShell SDK

V2.0 of the Microsoft Graph PowerShell SDK is now in preview. The good news is that V2.0 delivers some nice advances. The bad news is that it does nothing to cure the weaknesses outlined here. I’ve expressed a strong opinion that Microsoft should fix the fundamental problems in the SDK before doing anything else.

I’m told that the root cause of many of the issues is the AutoRest process Microsoft uses to generate the Microsoft Graph PowerShell SDK cmdlets from Graph API metadata. It looks like we’re stuck between a rock and a hard place. We benefit enormously by having the SDK cmdlets but the process that makes the cmdlets available introduces its own issues. Let’s hope that Microsoft gets to fix (or replace) AutoRest and deliver an SDK that’s better aligned with PowerShell standards before our remaining hair falls out due to the frustration of dealing with unpredictable cmdlet behavior.


Insight like this doesn’t come easily. You’ve got to know the technology and understand how to look behind the scenes. Benefit from the knowledge and experience of the Office 365 for IT Pros team by subscribing to the best eBook covering Office 365 and the wider Microsoft 365 ecosystem.

10 Replies to “Mastering the Foibles of the Microsoft Graph PowerShell SDK”

  1. Hey Tony!

    For this example “[array]$Logs = Get-MgAuditLogSignIn -Filter “UserPrincipalName eq ‘james.ryan@office365itpros.com'” -All” there is a working solution that Microsoft use in the backend if we analyze the Graph requests during filtering through the portal:

    [array]$Logs = Get-MgAuditLogSignIn -Filter “(tolower(UserPrincipalName) eq ‘$($UPN.ToLower())”” -All

    Unfortunately, Graph tolower filter query parameter is not working with all properties that we want to filter on.

    1. It’s still an inconsistency because the bloody filter should work without manipulation…

      BTW, did you paste the code in correctly? It didn’t work for me…. Get-MgAuditLogSignIn : Invalid filter clause

      1. Sorry, I made a mistake with parentheses. This is working example:
        [array]Get-MgAuditLogSignIn -Filter “tolower(UserPrincipalName) eq ‘$($UPN.ToLower())'” -All

        But I completely agree with you that it would be better not to have to do this for all Graph cmdlets filter expressions.

  2. Tony,
    Great post (even though a little frustrating).
    Regarding the ‘additional properties’ – I think those uppercase/lowercase issues existed even before, in the AzureAD PS module.
    I often refer to the ‘get-azureaduser’ extensionProperty attribute. Among other additional details, it provides for the dirSynced objects the distinguishedName of the on-prem object. The name of that sub-attribute (within the ‘extensionProperty’ attribute) is ‘onPremisesDistinguishedName’ and it has to be written with capital ‘P’, ‘D’ and ‘N’ – otherwise it doesn’t work. The same stays for ‘createdDateTime’ sub-attribute, and probably with other sub-attributes as well (haven’t tested them all).
    So even if the strange behavior for $null variable or no support for pipeline (which sounds weird, as in my opinion pipeline is one of the strongest powers of PS), sometimes not only Graph SDK is to blame.

    1. I think the source of those problems is the Azure AD Graph… which is now being deprecated, but whose code and metadata advanced into the Microsoft Graph and is picked up by AutoREST when it generates the SDK cmdlets… Decisions taken years ago can have big consequences.

  3. Well said. It’s obvious that in developing the Microsoft PowerShell Graph API Microsoft lost sight of the 80/20 rule – 80% of people only use 20% of the functionality of the software. In the old modules, the 20% that most people probably use (user management, group management, license management etc) worked fairly well, including things like pipeline support. Microsoft now move to Graph, and one of the clear benefits is that you can access nearly 100% of the API using the PowerShell cmdlets. But the problem is – *most people don’t care* – we just want the 20% that we need to work smoothly.

    They would do well to focus on that ‘core functionality’ before trying to do more work on the stuff many people will touch rarely, if ever.

  4. “The workaround is to store the set of objects in an array and then process the objects with a ForEach loop.”
    That’s like…back to VBS era from 15 years ago ? Sounds insane to me…

      1. This SDK reminds me of Visual Studio Code : a tool made by developers for developers, bloated with tons of useless stuff for admins and regressions (like a Windows 3.11 UI).

        Admins need efficient, intuitive, consistent, modular, well-documented scripting tools. A lot of us do not use nor write apps for day-to-day tasks like querying account properties.
        Just rewriting PS scripts to remove the pipeline will make them much more complex, long, and hard to maintain. There was a reason Powershell was a welcomed revolution so many years ago !

        I really don’t understand how could it come to this. VBScript as a leading technology for Azure scripting in the next ten years at least, really ?

        Sorry for the rant. It feels like Azure tooling is going backwards since the Graph stack showed up, which is very frustrating. We could use at least more and better communication from Microsoft about this.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.