This code
foreach ($AU in $AUList) {
    $Code = $AU.CountryCode
    $Name = $AU.CountryName
    $params = @{
          displayName = "$Code" + "_Users"
          description = "A dynamic administrative unit for " + "$Name"
          membershipType = "Dynamic"
          membershipRule = "(user.dirSyncEnabled -eq True) and (user.country -eq $Code)"
          membershipRuleProcessingState = "On"
          visibility = "HiddenMembership"
    }
    $adminUnitObj = New-MgDirectoryAdministrativeUnit -BodyParameter $params
    }
results in the following error:
New-MgDirectoryAdministrativeUnit : Invalid operands found for operator -eq
At line:12 char:1
+ $adminUnitObj = New-MgDirectoryAdministrativeUnit -BodyParameter $par ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: ({ Headers = , b...istrativeUnit }:<>f__AnonymousType1`2) [New-MgDirectoryAdministrativeUnit
   _Create], Exception
    + FullyQualifiedErrorId : InvalidOperandsException,Microsoft.Graph.PowerShell.Cmdlets.NewMgDirectoryAdministrativeUnit_Create
My understanding is that this is a string and the actual contents should not matter.
I'm not sure what part of my membership rule is upsetting it, but I have tried setting them both available variables and Strings. Could someone please help me pinpoint what it's having trouble with?
There are 2 clear issues with your dynamic filter, one of them I'm not quite sure (correct me if I'm wrong) but if I recall correctly, booleans are case-sensitive, so it should be true instead of True. The other issue is that the value for country is missing quotes, as shown in the docs:
| Properties | Allowed values | Usage | 
|---|---|---|
| country | Any string value or null | user.country -eq "value" | 
So, to fix this you, you should change your filter to:
membershipRule = "(user.dirSyncEnabled -eq true) and (user.country -eq `"$Code`")"
Because you're using an expandable string "...", to escape the inner " you can use back-ticks (`).
Another option, perhaps more readable and easy to understand could be to use string interpolation via the -f operator, in this case you'd use single quotes outside:
membershipRule = '(user.dirSyncEnabled -eq true) and (user.country -eq "{0}")' -f $Code
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With