Forum Discussion

luca_duente's avatar
luca_duente
Copper Contributor
Sep 30, 2024

Exchange Online Powershell get User without Address Book Policy

Hey,
I have the following problem. I have a script that assigns users to an ABP based on the attributes Company and Department.

 

function Set-ABPstoUser
{
    Write-StatusLog -Type "SECTION" -Message "Assigne ABPs" -StatusFile $status_file
    $abps = Get-AddressBookPolicy
    $counter = 0

    foreach ($abp in $abps)
    {
        $abpName = $abp.Name
        $abpCompanyName = $abpName.Split('_')[1]
        $abpDepartment = $abpName.Split('_')[2]

        $usersWithCompanyAndDepartment = Get-User -Filter "Company -eq '$abpCompanyName' -and Department -eq '$abpDepartment'"

        Write-StatusLog -Type "SECTION" -Message "Log of Assigments" -StatusFile $status_file

        foreach ($user in $usersWithCompanyAndDepartment)
        {
            Set-Mailbox -Identity $user.Identity -AddressBookPolicy $abpName
            Write-Host "Die ABP '$abpName' wurde der Mailbox '$($user.DisplayName)' zugewiesen."
            $counter++
        }
        Write-StatusLog -Type "COMPLETE" -Message "Log of Assigments" -StatusFile $status_file

        Write-StatusLog -Type "MESSAGE" -Message "$counter User geht assigned new ABP" -StatusFile $status_file
    }
    Write-StatusLog -Type "COMPLETE" -Message "Assigne ABPs" -StatusFile $status_file
}

There are currently 2 thousand mailboxes, but this number will rise to 50 thousand mailboxes. The script currently takes 8 minutes to assign 2 thousand mailboxes. The problem is that mailboxes that already have an ABP are also touched. This makes the script extremely long and unnecessary.
So far I have not been able to filter for mailboxes that do not have an ABP.
I have tried the following (the first one throws an error saying it cannot be filtered and the second one runs through all of them without any changes):

$usersWithCompanyAndDepartment = Get-User -Filter "Company -eq '$abpCompanyName' -and Department -eq '$abpDepartment' -and AddressBookPolicy -eq `$null"
$usersWithCompanyAndDepartment = Get-User -Filter "Company -eq '$abpCompanyName' -and Department -eq '$abpDepartment'"
$usersWithoutABP = $usersWithCompanyAndDepartment | Where-Object { $_.AddressBookPolicy -eq $null }


$usersWithCompanyAndDepartment = Get-Mailbox -Filter "Company -eq '$abpCompanyName' -and Department -eq '$abpDepartment'"
$usersWithoutABP = $usersWithCompanyAndDepartment | Where-Object { $_.AddressBookPolicy -eq $null }

Do you have any ideas what can be done?

Thank you very much!

Luca

 

    • luca_duente's avatar
      luca_duente
      Copper Contributor

      VasilMichev 

      The problem is that in addition to the AddressBookPolicy filter, I also add another filter to determine which company the user belongs to. 
      Like:

      Get-Mailbox -ResultSize Unlimited -Filter "Company -eq 'MTS' -and AddressBookPolicy -eq '$null'"

      Or

      Get-User -ResultSize Unlimited -Filter "Company -eq 'MTS' -and AddressBookPolicy -eq '$null'"

       

      Both Versions doesn't work: 

       

      Write-ErrorMessage : Cannot process argument transformation on parameter 'Filter'. Cannot convert value "Company -eq 'MTS' -and AddressBookPolicy -eq ''" to type "System.String". Error: ""AddressBookPolicy" is not a recognized filterable property. Valid property names are: AccountDisabled, AdministrativeUnits, Alias, AllowUMCallsFromNonUsers, Altitude,
      AltSecurityIdentities, ArchiveDatabaseRaw, ArchiveDomain, ArchiveGuid, ArchiveRelease, AssistantName, AuthenticationPolicy, C, CertificateSubject, City, Co, Company, ConfigurationBitmapRaw, ConfigurationUnit, ConfigurationXMLRaw, ConsumerNetID, CorrelationId, CorrelationIdRaw, CountryCode, CountryOrRegion, CustomAttribute1, CustomAttribute10, CustomAttribute11,
      CustomAttribute12, CustomAttribute13, CustomAttribute14, CustomAttribute15, CustomAttribute2, CustomAttribute3, CustomAttribute4, CustomAttribute5, CustomAttribute6, CustomAttribute7, CustomAttribute8, CustomAttribute9, Database, DataEncryptionPolicy, Department, DesiredMailboxWorkloadsModified, DirectReports, DisabledArchiveGuid, DisplayName, DistinguishedName,
      ElcMailboxFlags, EmailAddresses, ExchangeGuid, ExchangeObjectId, ExchangeObjectIdRaw, ExchangeSidHistory, ExchangeUserAccountControl, ExchangeVersion, ExtensionCustomAttribute1, ExtensionCustomAttribute2, ExtensionCustomAttribute3, ExtensionCustomAttribute4, ExtensionCustomAttribute5, ExternalDirectoryObjectId, ExternalDirectoryObjectIdRaw, Fax, FirstName, GroupType, Guid,
      HABSeniorityIndex, HomePhone, Id, ImmutableSid, InformationBarrierSegments, Initials, InPlaceHoldsRaw, IsDirSynced, IsInactiveMailbox, IsLinked, IsSecurityPrincipal, IsSoftDeletedByDisable, IsSoftDeletedByRemove, LastName, Latitude, LegacyExchangeDN, LegacyExchangeDNRaw, LinkMetadata, Longitude, MailboxDatabasesRaw, MailboxGuidsRaw, MailboxLocationsRaw, MailboxRelease,
      Manager, MasterAccountSid, MemberOfGroup, MobilePhone, Name, NetID, Notes, NTSecurityDescriptor, ObjectCategory, ObjectClass, Office, OrganizationalUnitRoot, OriginalNetID, OtherFax, OtherHomePhone, OtherTelephone, Pager, PasswordLastSetRaw, Phone, PhoneticDisplayName, PostalCode, PostOfficeBox, PreviousRecipientTypeDetails, ProtocolSettings, ProvisioningFlags,
      RawCanonicalName, RawName, RecipientSoftDeletedStatus, RecipientType, RecipientTypeDetails, RecipientTypeDetailsValue, RemotePowerShellEnabled, ReplicationSignature, SamAccountName, ServerLegacyDN, ShadowAlias, ShadowAssistantName, ShadowC, ShadowCity, ShadowCo, ShadowCompany, ShadowCountryCode, ShadowDepartment, ShadowDisplayName, ShadowEmailAddresses, ShadowFax,
      ShadowFirstName, ShadowHomePhone, ShadowInitials, ShadowLastName, ShadowManager, ShadowMobilePhone, ShadowNotes, ShadowOffice, ShadowOtherFax, ShadowOtherHomePhone, ShadowOtherTelephone, ShadowPager, ShadowPhone, ShadowPostalCode, ShadowStateOrProvince, ShadowStreetAddress, ShadowTelephoneAssistant, ShadowTitle, ShadowWebPage, ShadowWhenSoftDeleted, ShadowWindowsLiveID,
      Sid, SidHistory, SidHistoryRaw, SidRaw, SimpleDisplayName, SKUAssigned, StateOrProvince, StreetAddress, StsRefreshTokensValidFrom, TelephoneAssistant, Title, UMCallingLineIds, UMDtmfMap, UMRecipientDialPlanId, UpgradeRequest, UpgradeStatus, UserAccountControl, UserPrincipalName, UserPrincipalNameRaw, VoiceMailSettings, WebPage, WhenChanged, WhenChangedRaw, WhenChangedUTC,
      WhenCreated, WhenCreatedRaw, WhenCreatedUTC, WhenIBSegmentChanged, WhenSoftDeleted, WindowsEmailAddress, WindowsLiveID.
      "Company -eq 'MTS' -and AddressBookPolicy -eq ''" at position 24."
      In C:\Users\luca_\AppData\Local\Temp\tmpEXO_p4wnpmma.ku1\tmpEXO_p4wnpmma.ku1.psm1:1205 Zeichen:13
      +             Write-ErrorMessage $ErrorObject
      +             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
          + CategoryInfo          : NotSpecified: (:) [get-User], ParameterTransformationException
          + FullyQualifiedErrorId : [Server=BEUP281MB3525,RequestId=62a842b8-3e46-0f5d-4e66-88fd95c7908a,TimeStamp=Fri, 04 Oct 2024 14:39:21 GMT],Write-ErrorMessage
      Write-ErrorMessage : Cannot process argument transformation on parameter 'Filter'. Cannot convert value "Company -eq 'MTS' -and AddressBookPolicy -eq ''" to type "System.String". Error: ""Company" is not a recognized filterable property. Valid property names are: AcceptMessagesOnlyFrom, AcceptMessagesOnlyFromDLMembers, AccountDisabled, AddressBookPolicy,
      AddressListMembership, AdministrativeUnits, AggregatedMailboxGuids, AggregatedMailboxGuidsRaw, Alias, AltSecurityIdentities, ArbitrationMailbox, ArchiveDatabase, ArchiveDatabaseRaw, ArchiveDomain, ArchiveGuid, ArchiveName, ArchiveQuota, ArchiveRelease, ArchiveState, ArchiveStatus, ArchiveWarningQuota, AuditAdminFlags, AuditDelegateAdminFlags, AuditDelegateFlags,
      AuditEnabled, AuditLogAgeLimit, AuditOwnerFlags, BypassModerationFrom, BypassModerationFromDLMembers, CalendarLoggingQuota, CalendarRepairDisabled, Certificate, ComplianceTagHoldApplied, ConfigurationBitmapRaw, ConfigurationUnit, ConfigurationXMLRaw, CorrelationId, CorrelationIdRaw, CustomAttribute1, CustomAttribute10, CustomAttribute11, CustomAttribute12,
      CustomAttribute13, CustomAttribute14, CustomAttribute15, CustomAttribute2, CustomAttribute3, CustomAttribute4, CustomAttribute5, CustomAttribute6, CustomAttribute7, CustomAttribute8, CustomAttribute9, Database, DataEncryptionPolicy, DefaultPublicFolderMailbox, DelayHoldApplied, DelayReleaseHoldApplied, DeletedItemFlags, DeliverToMailboxAndForward, DisabledArchiveDatabase,
      DisabledArchiveGuid, DisplayName, DistinguishedName, ElcExpirationSuspensionEndDate, ElcExpirationSuspensionStartDate, ElcMailboxFlags, ElcPolicyTemplate, EmailAddresses, EmailAddressPolicyEnabled, EnforcedTimestamps, ExchangeGuid, ExchangeObjectId, ExchangeObjectIdRaw, ExchangeSecurityDescriptorRaw, ExchangeUserAccountControl, ExchangeVersion, ExtensionCustomAttribute1,
      ExtensionCustomAttribute2, ExtensionCustomAttribute3, ExtensionCustomAttribute4, ExtensionCustomAttribute5, ExternalDirectoryObjectId, ExternalDirectoryObjectIdRaw, ExternalOofOptions, ForwardingAddress, ForwardingSmtpAddress, GeneratedOfflineAddressBooks, GenericForwardingAddress, GrantSendOnBehalfTo, GroupType, Guid, HiddenFromAddressListsEnabled,
      HiddenFromAddressListsValue, Id, ImmutableId, IncludeInGarbageCollection, InPlaceHolds, InPlaceHoldsRaw, InternalUsageLocation, IsDirSynced, IsExcludedFromServingHierarchy, IsHierarchyReady, IsHierarchySyncEnabled, IsInactiveMailbox, IsLinked, IsMachineToPersonTextMessagingEnabled, IsMailboxEnabled, IsMonitoringMailbox, IsPersonToPersonTextMessagingEnabled, IsResource,
      IsShared, IsSoftDeletedByDisable, IsSoftDeletedByRemove, IssueWarningQuota, JournalArchiveAddress, LanguagesRaw, LastExchangeChangedTime, LegacyExchangeDN, LegacyExchangeDNRaw, LinkMetadata, LitigationHoldDate, LitigationHoldEnabled, LitigationHoldOwner, MailboxContainerGuid, MailboxDatabasesRaw, MailboxGuidsRaw, MailboxLocationsRaw, MailboxMoveBatchName, MailboxMoveFlags,
      MailboxMoveRemoteHostName, MailboxMoveSourceArchiveMDB, MailboxMoveSourceMDB, MailboxMoveStatus, MailboxMoveTargetArchiveMDB, MailboxMoveTargetMDB, MailboxPlan, MailboxRelease, MailTipTranslations, ManagedFolderMailboxPolicy, MasterAccountSid, MaxBlockedSenders, MaxReceiveSize, MaxSafeSenders, MaxSendSize, MemberOfGroup, MessageHygieneFlags, ModeratedBy, ModerationEnabled,
      ModerationFlags, Name, NetID, NonCompliantDevices, NTSecurityDescriptor, ObjectCategory, ObjectClass, Office, OfflineAddressBook, OrganizationalUnitRoot, OriginalNetID, PasswordLastSetRaw, PersistedCapabilities, PitrEnabled, PitrPaused, PoliciesExcluded, PoliciesIncluded, PreviousDatabase, PrimarySmtpAddress, ProhibitSendQuota, ProhibitSendReceiveQuota, ProtocolSettings,
      ProvisioningFlags, QueryBaseDN, RawCanonicalName, RawCapabilities, RawIssueWarningQuota, RawName, RawProhibitSendQuota, RawProhibitSendReceiveQuota, RawRecoverableItemsQuota, RawRecoverableItemsWarningQuota, RecipientLimits, RecipientSoftDeletedStatus, RecipientType, RecipientTypeDetails, RecipientTypeDetailsValue, RecoverableItemsQuota, RecoverableItemsWarningQuota,
      RejectMessagesFrom, RejectMessagesFromDLMembers, RemoteAccountPolicy, RemotePowerShellEnabled, RemoteRecipientType, ReplicationSignature, RequireAllSendersAreAuthenticated, ResourceCapacity, ResourceCustom, ResourceMetaData, ResourcePropertiesDisplay, ResourceProvisioningOptions, ResourceSearchProperties, ResourceType, RetainDeletedItemsFor, RetentionComment,
      RetentionPolicy, RetentionUrl, RoleAssignmentPolicy, RulesQuota, SamAccountName, SCLDeleteThresholdInt, SCLJunkThresholdInt, SCLQuarantineThresholdInt, SCLRejectThresholdInt, SecurityProtocol, ServerLegacyDN, ServerName, ShadowAlias, ShadowDisplayName, ShadowEmailAddresses, ShadowOffice, ShadowWhenSoftDeleted, ShadowWindowsLiveID, SharedEmailDomainStateLastModified,
      SharedEmailDomainTenant, SharedWithTargetSmtpAddress, SharingPolicy, SimpleDisplayName, SingleItemRecoveryEnabled, SKUAssigned, SMimeCertificate, SourceAnchor, StsRefreshTokensValidFrom, TextMessagingState, ThrottlingPolicy, ThumbnailPhoto, TransportSettingFlags, UCSImListMigrationCompleted, UMDtmfMap, UMEnabled, UMEnabledFlags, UMSpokenName, UnifiedMailboxAccount,
      UsageLocation, UseDatabaseQuotaDefaults, UserAccountControl, UserPrincipalName, UserPrincipalNameRaw, UsnCreated, WasInactiveMailbox, WhenChanged, WhenChangedRaw, WhenChangedUTC, WhenCreated, WhenCreatedRaw, WhenCreatedUTC, WhenMailboxCreated, WhenSoftDeleted, WindowsEmailAddress, WindowsLiveID.
      "Company -eq 'MTS' -and AddressBookPolicy -eq ''" at position 1."
      In C:\Users\luca_\AppData\Local\Temp\tmpEXO_p4wnpmma.ku1\tmpEXO_p4wnpmma.ku1.psm1:1205 Zeichen:13
      +             Write-ErrorMessage $ErrorObject
      +             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
          + CategoryInfo          : NotSpecified: (:) [Get-Mailbox], ParameterTransformationException
          + FullyQualifiedErrorId : [Server=BEUP281MB3525,RequestId=285a81fa-6d2c-f78a-77f4-1439fcd5c6fe,TimeStamp=Fri, 04 Oct 2024 14:39:51 GMT],Write-ErrorMessage

       

      Some other Ideas?

      • VasilMichev's avatar
        VasilMichev
        MVP
        Company is a user-level property, not mailbox one (i.e. you don't see it in the output of Get-Mailbox). So use this instead:

        Get-Recipient -Filter "AddressBookPolicy -eq `$null -and Company -eq 'MTS'"

Resources