Components All New MacOS Windows Linux iOS
Examples Mac & Win Server Client Guides Statistic FMM Blog Deprecated Old

LDAP.Search

Performs a search.

Component Version macOS Windows Linux Server iOS SDK
LDAP 6.0 ✅ Yes ✅ Yes ✅ Yes ✅ Yes ❌ No
MBS( "LDAP.Search"; LDAPRef; Base; Scope; Filter; Attributes { ; AttributesOnly; Timeout; Size Limit } )   More

Parameters

Parameter Description Example Flags
LDAPRef The reference number for the LDAP connection. $ldap
Base the distinguished name of the entry at which to start the search.
Scope Value to indicate the search scope. Can be:

Base: Search the base entry only.
OneLevel: Search all entries in the first level below the base entry, excluding the base entry.
Subtree: Search the base entry and all entries in the tree below the base.

On Mac can also be Children.
"Subtree"
Filter A text that specifies the search filter.
Attributes List indicating which attributes to return for each matching entry. "cn¶sn"
AttributesOnly Boolean value that should be 0 if both attribute types and values are to be returned, 1 if only types are required. 0 Optional
Timeout Timeout in seconds.
Specifies both the local search time-out value, in seconds, and the operation time limit that is sent to the server within the search request.
10 Optional
Size Limit Limit on the number of entries to return from the search.
A value of zero indicates no limit.
Optional

Result

Returns OK or error.

Description

Performs a search.
Searches the LDAP directory and returns a requested set of attributes for each matched entry.

On success, you can use LDAP.SearchResult.Count to find out the number of entries found.

Examples

Search for name:

MBS( "LDAP.Search"; $ldap; "dc=example,dc=com"; "Subtree"; "(sn=Jensen)")

Find entries with a givenName:

MBS("LDAP.Search"; $ldap; ""; "Subtree"; "(givenName=*)"; ""; 0; 20; 999)

Example script to create new group:

# ========================================
# Purpose:
# Creates a new AD Group
# Returns:
# $error = Error code if unsuccessful
# $error = 0 for success
# $resultText = Text summary of the success or error
# Parameters:
# $serverName
# $serverDomain
# $baseOU
# $groupName (base name only, excluding domain name)
# $groupDomain
# Called from:
# (script) "Set AD Group (worker)"
# Author:
# John Munro (HJM) from Deutsche Schule Tokyo Yokohama
# Notes:
# none
# History:
# 2021-05-26 HJM - created from DySIS-StudentAdmin version
# ========================================
#
Set Variable [ $! ; Value: #Assign ( Get ( ScriptParameter ) ) ]
#
# The branch in LDAP containing all active entries
Set Variable [ $searchBase ; Value: "dc=dsty,dc=ac,dc=jp" ]
#
Set Error Capture [ On ]
#
# If debugging these parameters will be empty so fill with test data
If [ $serverName = "" ]
    Set Variable [ $serverName ; Value: "sn-sys-dc1" ]
End If
If [ $serverDomain = "" ]
    Set Variable [ $serverDomain ; Value: "schulnetz.dsty.ac.jp" ]
End If
If [ $baseOU = "" ]
    Set Variable [ $baseOU ; Value: $searchBase ]
End If
If [ $groupName = "" ]
    Set Variable [ $groupName ; Value: "Test-Group" ]
End If
If [ $groupDomain = "" ]
    Set Variable [ $groupDomain ; Value: "dsty.ac.jp" ]
End If
#
#
# Bind to LDAP
Perform Script [ Specified: From list ; “LDAPServerBind” ; Parameter: # ( "serverName" ; $serverName ) & # ( "serverDomain" ; $serverDomain ) ]
# Returns $result, $ldap
#
Set Variable [ $! ; Value: #Assign ( Get ( ScriptResult ) ) ]
If [ $error <> 0 ]
    Show Custom Dialog [ "LDAP error" ; $resultText ]
    Exit Script [ Text Result: # ( "error" ; $result ) & # ( "resultText" ; "LDAP error: " & $resultText ) ]
End If
#
#
# Sanity check: Ensure that group is not already present in AD
Set Variable [ $LDAPFilter ; Value: "(sAMAccountName=" & $groupName & ")" ]
Set Variable [ $result ; Value: MBS ( "LDAP.Search" ; $ldap ; $searchBase ; "subtree" ; $LDAPFilter ; "" ; 0 ; 20 ; 9999 ) ]
#
Set Variable [ $entryCount ; Value: MBS("LDAP.SearchResult.Count"; $ldap) ]
If [ $entryCount > 0 ]
    # The group is already present in AD so exit with error
    Set Variable [ $resultText ; Value: "The sAMAccountName is already present in AD: \" & $groupName" ]
    Show Custom Dialog [ "LDAP Error" ; $resultText ]
    # Cleanup
    Set Variable [ $releaseResult ; Value: MBS("LDAP.Release"; $ldap) ]
    Exit Script [ Text Result: # ( "error" ; 1 ) & # ( "resultText" ; "LDAP error: " & $resultText ) ]
End If
#
#
# Sanity check: Ensure the DN is not already present in AD
Set Variable [ $groupDN ; Value: "CN=" & $groupName & "," & $baseOU ]
Set Variable [ $LDAPFilter ; Value: "" ]
Set Variable [ $result ; Value: MBS ( "LDAP.Search" ; $ldap ; $groupDN ; "base" ; $LDAPFilter ; "" ; 0 ; 4 ; 1 ) ]
#
Set Variable [ $entryCount ; Value: MBS("LDAP.SearchResult.Count"; $ldap) ]
If [ $entryCount > 0 ]
    # The groupname is already present in AD so exit with error
    Set Variable [ $resultText ; Value: "The DN is already present in AD: " & $groupDN ]
    Show Custom Dialog [ "LDAP Error" ; $resultText ]
    # Cleanup
    Set Variable [ $releaseResult ; Value: MBS("LDAP.Release"; $ldap) ]
    Exit Script [ Text Result: # ( "error" ; 1 ) & # ( "resultText" ; "LDAP error: " & $resultText ) ]
End If
#
#
# ===============================================================================================
# Group is confirmed not present in AD so proceed to create it
# Build the JSON for the Add
#
# AD attributes
Set Variable [ $objectClass ; Value: "{ \"operation\": \"Add\", \"name\": \"objectClass\", \"values\": [ \"top\", \"group\" ] }" ]
Set Variable [ $sAMAccountName ; Value: "{ \"operation\": \"Add\", \"name\": \"sAMAccountName\", \"value\": \"" & $groupName & "\" }" ]
Set Variable [ $cn ; Value: "{ \"operation\": \"Add\", \"name\": \"cn\", \"value\": \"" & $groupName & "\" }" ]
Set Variable [ $mail ; Value: "{ \"operation\": \"Add\", \"name\": \"mail\", \"value\": \"" & Lower ( $groupName & "@" & $groupDomain ) & "\" }" ]
#
# Add the JSON components together
Set Variable [ $json ; Value: "[" & $objectClass & "," & $sAMAccountName & "," & $cn & "," & $mail & "]" ]
#
# Attempt to add the groupDN record to the $baseOU
Set Variable [ $result ; Value: MBS( "LDAP.AddJSON" ; $ldap ; $groupDN ; $json ) ]
If [ MBS( "IsError" ) ]
    Set Variable [ $resultText ; Value: "Failed to add group." & ¶ & $result & ¶ & $json ]
    Show Custom Dialog [ "LDAP Error" ; $resultText ]
    # Cleanup
    Set Variable [ $releaseResult ; Value: MBS("LDAP.Release"; $ldap) ]
    Exit Script [ Text Result: # ( "error" ; $result ) & # ( "resultText" ; "LDAP error: " & $resultText ) ]
End If
#
#
# Cleanup
Set Variable [ $releaseResult ; Value: MBS("LDAP.Release"; $ldap) ]
Go to Layout [ original layout ; Animation: None ]
#
#
# Return error free result
Exit Script [ Text Result: # ( "error" ; 0 ) & # ( "resultText" ; "Group create success" ) ]

Example script get records:

# ========================================
# Purpose:
# Queries Active Directory from a server-side script
# This guarrantees the MBS plugin availability and that the MBS plugin has LDAP access to the Domain Controller
# Returns:
# $error = Error code if unsuccessful
# $error = 0 for success
# $resultText = Text summary of the success or error
# Parameters:
# $serverName
# $serverDomain
# $personIDs
# Called from:
# (script) "Get AD Records"
# Author:
# John Munro (HJM) from Deutsche Schule Tokyo Yokohama
# Notes:
# none
# History:
# 2020-06-15 HJM - created
# 2021-05-20 HJM - Replaced bind code with call to LDAPServerBind (including added parameter $serverDomain to all calls)
# 2021-05-21 HJM - modified result returned to be in #Assign variable method
# ========================================
#
Set Variable [ $! ; Value: #Assign ( Get ( ScriptParameter ) ) ]
#
# The branch in LDAP containing all active entries
Set Variable [ $searchBase ; Value: "dc=dsty,dc=ac,dc=jp" ]
#
Set Error Capture [ On ]
#
# If debugging these parameters will be empty so fill with test data
If [ $serverName = "" ]
    Set Variable [ $serverName ; Value: "sys-dc1" ]
End If
If [ $serverName = "" ]
    Set Variable [ $serverDomain ; Value: "dsty.ac.jp" ]
End If
If [ $personIDs = "" ]
    Set Variable [ $personIDs ; Value: "12345" ]
End If
#
# Jump to a working list populated with the records of the passed IDs
Set Field [ #Selector::SelectedPersonID ; $personIDs ]
Go to Layout [ “@People” (@People) ; Animation: None ]
Go to Related Record [ Show only related records ; From table: “#SelectedPerson” ; Using layout: “@People” (@People) ]
#
#
# Bind to LDAP
Perform Script [ Specified: From list ; “LDAPServerBind” ; Parameter: # ( "serverName" ; $serverName ) & # ( "serverDomain" ; $serverDomain ) ]
# Returns $error,$resultText, $ldap
#
Set Variable [ $! ; Value: #Assign ( Get ( ScriptResult ) ) ]
If [ $error <> 0 ]
    Go to Layout [ original layout ; Animation: None ]
    Show Custom Dialog [ "LDAP error" ; $resultText ]
    Exit Script [ Text Result: # ( "error" ; $error ) & # ( "resultText" ; "LDAP error: " & $resultText ) ]
End If
#
#
# Define search filter
Set Variable [ $usernameList ; Value: Substitute ( @People::Ac | DSTY | Username FoundSet_List ; "¶¶" ; "¶" ) //Remove any CR from the source field ]
Set Variable [ $LDAPFilter ; Value: "(|" & "(sAMAccountName=" & Substitute ( $usernameList ; "¶" ; ")(sAMAccountName=" ) & ")" & ")" ]
#
# Perform the search on LDAP
Set Variable [ $result ; Value: MBS ( "LDAP.Search" ; $ldap ; $searchBase ; "subtree" ; $LDAPFilter ; "" ; 0 ; 30 ; 9999 ) ]
#
# Record the search timestamp for all records (including those not present in AD)
Set Variable [ $LookupTimestamp ; Value: Get ( CurrentTimestamp ) ]
#
// # Check results
// Show Custom Dialog [ "JSON" ; MBS("LDAP.JSON"; $ldap) ]
#
Set Variable [ $foundInAD ; Value: MBS("LDAP.SearchResult.Count"; $ldap) ]
If [ $foundInAD > 0 ]
    #
    # extract the results
    Set Variable [ $jsonIndex ; Value: 0 ]
    Loop
        Set Variable [ $username ; Value: MBS("LDAP.SearchResult.AttributeValuesByName" ; $ldap ; $jsonIndex ; "sAMAccountName" ) ]
        #
        # find the record with DSTYUsername = $username
        Perform Find [ Restore ]
        #
        If [ Get ( FoundCount ) = 1 ]
            # There should only be one record found as DSTYUsername has unique values
            #
            # Populate the LDAP cache fields
            Set Field [ @People::Ac | LDAP | AD Network ; $serverDomain ]
            Set Field [ @People::Ac | LDAP | DataTimestamp ; $LookupTimestamp ]
            Set Field [ @People::Ac | LDAP | userDN ; MBS("LDAP.SearchResult.DistinguishedName"; $ldap; $jsonIndex) ]
            Set Field [ @People::Ac | LDAP | DisplayName ; MBS("LDAP.SearchResult.AttributeValuesByName" ; $ldap ; $jsonIndex ; "displayName" ) ]
            Set Field [ @People::Ac | LDAP | EmailAddr ; MBS("LDAP.SearchResult.AttributeValuesByName" ; $ldap ; $jsonIndex ; "mail" ) ]
            Set Field [ @People::Ac | LDAP | Groups | Raw ; MBS("LDAP.SearchResult.AttributeValuesByName" ; $ldap ; $jsonIndex ; "memberOf" ) ]
            Set Field [ @People::Ac | LDAP | PrivEmail ; MBS("LDAP.SearchResult.AttributeValuesByName" ; $ldap ; $jsonIndex ; "otherMailbox" ) ]
            Set Field [ @People::Ac | LDAP | PwdLastSet ; MBS("LDAP.SearchResult.AttributeValuesByName" ; $ldap ; $jsonIndex ; "pwdLastSet" ) ]
            Set Field [ @People::Ac | LDAP | userAccountControl ; MBS("LDAP.SearchResult.AttributeValuesByName" ; $ldap ; $jsonIndex ; "userAccountControl" ) ]
            Set Field [ @People::Ac | LDAP | Username ; $username ]
            #
            # Convert raw time from AD to a local Filemaker timestamp
            Set Variable [ $accountExpires ; Value: MBS("LDAP.SearchResult.AttributeValuesByName" ; $ldap ; $jsonIndex ; "accountExpires" ) ]
            If [ $accountExpires > 0 ]
                Set Variable [ $accountExpires ; Value: Timestamp ( Date ( 1 ; 1 ; 1601 ) ; Time ( 0 ; 0 ; 0 ) + 9 * 3600 ) + Round ( $accountExpires / 10000000 / 60 ; 0 ) * 60 ]
            Else
                Set Variable [ $accountExpires ; Value: "" ]
            End If
            Set Field [ @People::Ac | LDAP | accountExpires ; $accountExpires ]
            #
            # Convert raw time from AD to a local Filemaker timestamp
            Set Variable [ $lastLogon ; Value: MBS("LDAP.SearchResult.AttributeValuesByName" ; $ldap ; $jsonIndex ; "lastLogon" ) ]
            If [ $lastLogon > 0 ]
                Set Variable [ $lastLogon ; Value: Timestamp ( Date ( 1 ; 1 ; 1601 ) ; Time ( 0 ; 0 ; 0 ) + 9 * 3600 ) + Round ( $lastLogon / 10000000 / 60 ; 0 ) * 60 ]
            Else
                Set Variable [ $lastLogon ; Value: "" ]
            End If
            #
            # Update the lastLogon field with only if it is a more recent date
            Set Field [ @People::Ac | LDAP | LastLogon ; Max ( @People::Ac | LDAP | LastLogon ; $lastLogon ) ]
            #
        End If
        #
        Set Variable [ $jsonIndex ; Value: $jsonIndex + 1 ]
        Exit Loop If [ $jsonIndex >= $foundInAD ]
        #
    End Loop
    #
End If
#
# Check for records not updated (i.e. not present in AD)
#
# Refind the original people set
Set Field [ #Selector::SelectedPersonID ; $personIDs ]
Go to Related Record [ Show only related records ; From table: “#SelectedPerson” ; Using layout: “@People” (@People) ]
#
# Omit those that have just been updated
Constrain Found Set [ Restore ]
Set Variable [ $missingFromAD ; Value: Get ( FoundCount ) ]
#
# if there are any remaining, these were not found in the LDAP query, so clear the fields in case the entry was removed from AD
If [ $missingFromAD > 0 ]
    Replace Field Contents [ With dialog: Off ; @People::Ac | LDAP | DataTimestamp ; $LookupTimestamp ]
    Replace Field Contents [ With dialog: Off ; @People::Ac | LDAP | AD Network ; "" ]
    Replace Field Contents [ With dialog: Off ; @People::Ac | LDAP | DisplayName ; "" ]
    Replace Field Contents [ With dialog: Off ; @People::Ac | LDAP | userDN ; "" ]
    Replace Field Contents [ With dialog: Off ; @People::Ac | LDAP | EmailAddr ; "" ]
    Replace Field Contents [ With dialog: Off ; @People::Ac | LDAP | Groups | Raw ; "" ]
    Replace Field Contents [ With dialog: Off ; @People::Ac | LDAP | LastLogon ; "" ]
    Replace Field Contents [ With dialog: Off ; @People::Ac | LDAP | PrivEmail ; "" ]
    Replace Field Contents [ With dialog: Off ; @People::Ac | LDAP | PwdLastSet ; "" ]
    Replace Field Contents [ With dialog: Off ; @People::Ac | LDAP | userAccountControl ; "" ]
    Replace Field Contents [ With dialog: Off ; @People::Ac | LDAP | Username ; "" ]
    Replace Field Contents [ With dialog: Off ; @People::Ac | LDAP | accountExpires ; "" ]
End If
#
# Cleanup
Set Variable [ $releaseResult ; Value: MBS("LDAP.Release"; $ldap) ]
Go to Layout [ original layout ; Animation: None ]
#
#
# Return error free result
Exit Script [ Text Result: # ( "error" ; 0 ) & # ( "resultText" ; "Staff found and updated from AD: " & $foundInAD & ¶ & "New staff needing to be added to AD: " & $missingFromAD ) ]

Example script to create an user:

# ========================================
# Purpose:
# If the user is not present in AD, create a new user in Pre-handover OU and add the groups defined in DySIS
# Returns:
# 0 for success
# Errot text if unsuccessful
# Parameters:
# $serverName
# $userName
# $userDomain
# $userEmail
# $fullName
# $surname
# $givenName
# $userOU
# $groups (base names only, excluding domain names)
# $userPassword
# Called from:
# (script) Create AD User account
# Author:
# John Munro (HJM) from Deutsche Schule Tokyo Yokohama
# Notes:
# none
# History:
# 2020-06-30 HJM - created
# 2020-09-10 HJM - modified to add parameter $userOU
# 2020-12-18 HJM - modified PasswordSet to use external subroutine rather than local code
# 2021-05-20 HJM - Replaced bind code with call to LDAPServerBind (including added parameter $serverDomain to all calls)
# ========================================
#
Set Variable [ $! ; Value: #Assign ( Get ( ScriptParameter ) ) ]
#
# ===============================================================================================
# If debugging these parameters will be empty so fill with test data
If [ $serverName = "" ]
    Set Variable [ $serverName ; Value: "sys-dc1" ]
End If
If [ $serverName = "" ]
    Set Variable [ $serverDomain ; Value: "dsty.ac.jp" ]
End If
If [ $userName = "" ]
    Set Variable [ $userName ; Value: "DySIStestUser" ]
End If
If [ $userDomain = "" ]
    Set Variable [ $userDomain ; Value: "dsty.ac.jp" ]
End If
If [ $userEmail = "" ]
    Set Variable [ $userEmail ; Value: "dysistestUser@dsty.test" ]
End If
If [ $userPassword = "" ]
    Set Variable [ $userPassword ; Value: "Welcome2" ]
End If
If [ $fullName = "" ]
    Set Variable [ $fullName ; Value: "DySIS testUser" ]
End If
If [ $surname = "" ]
    Set Variable [ $surname ; Value: "testUser" ]
End If
If [ $givenName = "" ]
    Set Variable [ $givenName ; Value: "DySIStest" ]
End If
If [ $userOU = "" ]
    Set Variable [ $userOU ; Value: "OU=Pre-handover,OU=DSTY Groups,DC=dsty,DC=ac,DC=jp" ]
End If
# Note $groups as an empty set is a valid condition so this should NOT be filled if empty
#
#
# Bind to LDAP
Perform Script [ Specified: From list ; “LDAPServerBind” ; Parameter: # ( "serverName" ; $serverName ) & # ( "serverDomain" ; $serverDomain ) ]
# Returns $error,$resultText, $ldap
#
Set Variable [ $! ; Value: #Assign ( Get ( ScriptResult ) ) ]
If [ $error <> 0 ]
    Go to Layout [ original layout ; Animation: None ]
    Show Custom Dialog [ "LDAP error" ; $resultText ]
    Exit Script [ Text Result: # ( "error" ; $error ) & # ( "resultText" ; "LDAP error: " & $resultText ) ]
End If
#
#
# Sanity check: Ensure that user is not already present in AD
#
Set Variable [ $LDAPFilter ; Value: "(sAMAccountName=" & $userName & ")" ]
Set Variable [ $result ; Value: MBS ( "LDAP.Search" ; $ldap ; $searchBase ; "subtree" ; $LDAPFilter ; "" ; 0 ; 20 ; 9999 ) ]
#
Set Variable [ $entryCount ; Value: MBS("LDAP.SearchResult.Count"; $ldap) ]
If [ $entryCount > 0 ]
    # The username is already present in AD so exit with error
    Set Variable [ $errorText ; Value: "The sAMAccountName is already present in AD: \" & $userName" ]
    Show Custom Dialog [ "LDAP Error" ; $errorText ]
    # Cleanup
    Set Variable [ $releaseResult ; Value: MBS("LDAP.Release"; $ldap) ]
    Exit Script [ Text Result: "LDAP error. " & $errorText ]
End If
#
# Sanity check: Ensure the DN is not already present in AD
#
Set Variable [ $personDN ; Value: "CN=" & $fullName & "," & $userOU ]
Set Variable [ $LDAPFilter ; Value: "" ]
Set Variable [ $result ; Value: MBS ( "LDAP.Search" ; $ldap ; $personDN ; "base" ; $LDAPFilter ; "" ; 0 ; 4 ; 1 ) ]
#
Set Variable [ $entryCount ; Value: MBS("LDAP.SearchResult.Count"; $ldap) ]
If [ $entryCount > 0 ]
    # The username is already present in AD so exit with error
    Set Variable [ $errorText ; Value: "The DN is already present in AD: " & $personDN ]
    Show Custom Dialog [ "LDAP Error" ; $errorText ]
    # Cleanup
    Set Variable [ $releaseResult ; Value: MBS("LDAP.Release"; $ldap) ]
    Exit Script [ Text Result: "LDAP error. " & $errorText ]
End If
#
#
# ===============================================================================================
# User is confirmed not present in AD so proceed to create it
# Build the JSON for the Add
#
# AD attributes
Set Variable [ $objectClass ; Value: "{ \"operation\": \"Add\", \"name\": \"objectClass\", \"values\": [ \"top\", \"person\", \"organizationalPerson\", \"user\" ] }" ]
Set Variable [ $sAMAccountName ; Value: "{ \"operation\": \"Add\", \"name\": \"sAMAccountName\", \"value\": \"" & $userName & "\" }" ]
Set Variable [ $userPrincipalName ; Value: "{ \"operation\": \"Add\", \"name\": \"userPrincipalName\", \"value\": \"" & $userName & "@" & $userDomain & "\" }" ]
Set Variable [ $userAccountControl ; Value: "{ \"operation\": \"Add\", \"name\": \"userAccountControl\", \"value\": \"" & 544 & "\" }" //NB: 544 is [ NoPasswordRequired, NormalAccount ] ]
Set Variable [ $cn ; Value: "{ \"operation\": \"Add\", \"name\": \"cn\", \"value\": \"" & $fullName & "\" }" ]
Set Variable [ $displayName ; Value: "{ \"operation\": \"Add\", \"name\": \"displayName\", \"value\": \"" & $fullName & "\" }" ]
Set Variable [ $sn ; Value: "{ \"operation\": \"Add\", \"name\": \"sn\", \"value\": \"" & $surname & "\" }" ]
Set Variable [ $givenName ; Value: "{ \"operation\": \"Add\", \"name\": \"givenName\", \"value\": \"" & $givenName & "\" }" ]
Set Variable [ $mail ; Value: "{ \"operation\": \"Add\", \"name\": \"mail\", \"value\": \"" & $userEmail & "\" }" ]
#
# Add the JSON components together
Set Variable [ $json ; Value: "[" & $objectClass & "," & $sAMAccountName & "," & $userPrincipalName & "," & $userAccountControl & "," & $cn & "," & $displayName & "," & $sn & "," & $givenName & "," & $mail & "]" ]
#
# Attempt to add the personDN record to the default OU
Set Variable [ $result ; Value: MBS( "LDAP.AddJSON" ; $ldap ; $personDN ; $json ) ]
If [ MBS( "IsError" ) ]
    Set Variable [ $errorText ; Value: "Failed to add user." & ¶ & $result & ¶ & $json ]
    Show Custom Dialog [ "LDAP Error" ; $errorText ]
    # Cleanup
    Set Variable [ $releaseResult ; Value: MBS("LDAP.Release"; $ldap) ]
    Exit Script [ Text Result: "LDAP error. " & $errorText ]
End If
#
# ===============================================================================================
# Set the password
#
Perform Script [ Specified: From list ; “Set AD Password (worker)” ; Parameter: # ( "serverName" ; $serverName ) & # ( "serverDomain" ; $serverDomain ) & # ( "personDN" ; $personDN ) & # ( "userPassword" ; $userPassword ) ]
#
Set Variable [ $result ; Value: Get ( ScriptResult ) ]
If [ $result <> 0 ]
    Show Custom Dialog [ "Error setting the password" ; $result ]
    # Exit with failure
    Exit Script [ Text Result: "Error setting the password:¶" & $result ]
End If
#
#
# ===============================================================================================
# Set the userAccountControl to NormalAccount (512)
# Prior to setting the password, the account has a password not required attribute
#
# Build the JSON for the modify
Set Variable [ $json ; Value: "[{ \"operation\": \"Replace\", \"name\": \"userAccountControl\", \"value\": \"512\" }]" ]
#
# Attempt to modify the groupDN record
Set Variable [ $result ; Value: MBS( "LDAP.ModifyJSON" ; $ldap ; $personDN ; $json ) ]
If [ MBS( "IsError" ) ]
    Set Variable [ $errorText ; Value: "Failed to set account to 'Normal account (type 512)'." & ¶ & $result & ¶ & $json ]
    Show Custom Dialog [ "LDAP Error" ; $errorText ]
    # Cleanup
    Set Variable [ $releaseResult ; Value: MBS("LDAP.Release"; $ldap) ]
    Exit Script [ Text Result: "LDAP error. " & $errorText ]
End If
#
#
# Cleanup
Set Variable [ $releaseResult ; Value: MBS("LDAP.Release"; $ldap) ]
#
#
# ===============================================================================================
# Add the person to all the groups passed in $groups
#
Set Variable [ $groupDomain ; Value: $userDomain ]
#
Set Variable [ $groupIndex ; Value: 1 ]
Set Variable [ $groupCount ; Value: ValueCount ( $groups ) ]
If [ $groupCount > 0 ]
    #
    Loop
        Set Variable [ $groupName ; Value: GetValue ( $groups ; $groupIndex ) ]
        #
        If [ $groupName <> "" ]
            #
            # This worker script is already running on the server so do not nest it to a sub server script as this does not make sense nor work.
            Perform Script [ Specified: From list ; “Set AD Group (worker)” ; Parameter: # ( "serverName" ; $serverName ) & # ( "serverDomain" ; $serverDomain ) & # ( "operation" ; "Add" ) & # ( "personDN" ; $personDN ) & # ( "groupName" ; $groupName ) & # ( "groupDomain" ; $groupDomain ) ]
            #
            Set Variable [ $result ; Value: Get ( ScriptResult ) ]
            If [ $result <> 0 ]
                Show Custom Dialog [ "Add group error" ; $result ]
                Exit Script [ Text Result: $result ]
            End If
        End If
    #
    Set Variable [ $groupIndex ; Value: $groupIndex + 1 ]
    Exit Loop If [ $groupIndex > $groupCount ]
    #
    End Loop
End If
#
# Exit with a success result
Exit Script [ Text Result: 0 ]

Example script to assign an organization unit for an user:

# ========================================
# Purpose:
# Assigns the OU of a single AD user
# Returns:
# 0 for success
# Error text if unsuccessful
# Parameters:
# $serverName
# $serverDomain
# $personDN
# $targetOU (the full DN of the target OU)
# Called from:
# (script) "Set AD OU"
# Author:
# John Munro (HJM) from Deutsche Schule Tokyo Yokohama
# Notes:
# none
# History:
# 2020-07-10 HJM - created
# 2021-05-20 HJM - Replaced bind code with call to LDAPServerBind (including added parameter $serverDomain to all calls)
# ========================================
#
Set Variable [ $! ; Value: #Assign ( Get ( ScriptParameter ) ) ]
#
// # The branch in LDAP containing all active entries
// Set Variable [ $searchBase ; Value: "ou=DSTY Groups,dc=dsty,dc=ac,dc=jp" ]
#
Set Error Capture [ On ]
#
# If debugging these parameters will be empty so fill with test data
If [ $serverName = "" ]
    Set Variable [ $serverName ; Value: "sys-dc1" ]
End If
If [ $serverName = "" ]
    Set Variable [ $serverDomain ; Value: "dsty.ac.jp" ]
End If
If [ $personDN = "" ]
    Set Variable [ $personDN ; Value: "CN=DySIS testUser,OU=VerwaltungOU,OU=DSTY Groups,DC=dsty,DC=ac,DC=jp" ]
End If
If [ $targetOU = "" ]
    Set Variable [ $targetOU ; Value: "OU=Pre-handover,OU=DSTY Groups,DC=dsty,DC=ac,DC=jp" ]
End If
#
#
# Bind to LDAP
Perform Script [ Specified: From list ; “LDAPServerBind” ; Parameter: # ( "serverName" ; $serverName ) & # ( "serverDomain" ; $serverDomain ) ]
# Returns $error,$resultText, $ldap
#
Set Variable [ $! ; Value: #Assign ( Get ( ScriptResult ) ) ]
If [ $error <> 0 ]
    Go to Layout [ original layout ; Animation: None ]
    Show Custom Dialog [ "LDAP error" ; $resultText ]
    Exit Script [ Text Result: # ( "error" ; $error ) & # ( "resultText" ; "LDAP error: " & $resultText ) ]
End If
#
#
# Check the targetOU is valid (exit with error if not)
Set Variable [ $LDAPFilter ; Value: "" ]
Set Variable [ $result ; Value: MBS ( "LDAP.Search" ; $ldap ; $targetOU ; "base" ; $LDAPFilter ; "" ; 0 ; 4 ; 1 ) ]
If [ MBS("LDAP.SearchResult.DistinguishedName"; $ldap; 0 ) = $targetOU ]
    #
    # Check the target is an actual Organisational Unit
    Set Variable [ $objectClasses ; Value: MBS("LDAP.SearchResult.AttributeValuesByName" ; $ldap ; 0 ; "objectClass" ) ]
    #
    If [ FilterValues ( $objectClasses ; "organizationalUnit" ) = "" ]
        # The target is not an actual Organisational Unit so exit with error
        Set Variable [ $errorText ; Value: "Target is not an Organizational Unit." & ¶ & $targetOU & ¶ & $result ]
        Show Custom Dialog [ "LDAP Error" ; $errorText ]
        # Cleanup
        Set Variable [ $releaseResult ; Value: MBS("LDAP.Release"; $ldap) ]
        Exit Script [ Text Result: "LDAP error. " & $errorText ]
    End If
    #
End If
#
#
# Check the personDN is valid and update the dn to contain the targetOU
Set Variable [ $LDAPFilter ; Value: "" ]
Set Variable [ $result ; Value: MBS ( "LDAP.Search" ; $ldap ; $personDN ; "base" ; $LDAPFilter ; "" ; 0 ; 4 ; 1 ) ]
If [ MBS( "IsError" ) ]
    Set Variable [ $errorText ; Value: "Failed to locate the personDN." & ¶ & $personDN & ¶ & $result ]
    Show Custom Dialog [ "LDAP Error" ; $errorText ]
    # Cleanup
    Set Variable [ $releaseResult ; Value: MBS("LDAP.Release"; $ldap) ]
    Exit Script [ Text Result: "LDAP error. " & $errorText ]
End If
#
Set Variable [ $foundDN ; Value: MBS("LDAP.SearchResult.DistinguishedName"; $ldap; 0 ) ]
If [ $foundDN <> $personDN ]
    Set Variable [ $errorText ; Value: "The found record DN did not match personDN." & ¶ & "Found: " & $foundDN & ¶ & "PersonDN: " & $personDN & ¶ & $result ]
    Show Custom Dialog [ "LDAP Error" ; $errorText ]
    # Cleanup
    Set Variable [ $releaseResult ; Value: MBS("LDAP.Release"; $ldap) ]
    Exit Script [ Text Result: "LDAP error. " & $errorText ]
End If
#
// # Build the JSON for the modify
// Set Variable [ $json ; Value: "[{ \"operation\": \"Replace\", \"type\": \"distinguishedName\", \"value\": \"" & $newPersonDN & "\" }]" ]
#
# Attempt to move the user record to the new DN
Set Variable [ $cn ; Value: MBS("LDAP.SearchResult.AttributeValuesByName" ; $ldap ; 0 ; "cn" ) ]
Set Variable [ $rdn ; Value: "CN=" & $cn ]
Set Variable [ $deleteOldRdn ; Value: 1 ]
Set Variable [ $result ; Value: MBS( "LDAP.Rename" ; $ldap ; $personDN ; $rdn ; $targetOU ; $deleteOldRdn ) ]
If [ MBS( "IsError" ) ]
    Set Variable [ $errorText ; Value: "Failed to modify the personDN." & ¶ & "From: " & $personDN & ¶ & "To: " & $rdn & ¶ & "Under: " & $targetOU & ¶ & $result ]
    Show Custom Dialog [ "LDAP Error" ; $errorText ]
    # Cleanup
    Set Variable [ $releaseResult ; Value: MBS("LDAP.Release"; $ldap) ]
    Exit Script [ Text Result: "LDAP error. " & $errorText ]
End If
#
#
# Cleanup
Set Variable [ $releaseResult ; Value: MBS("LDAP.Release"; $ldap) ]
Go to Layout [ original layout ; Animation: None ]
#
#
# Return error free result
Exit Script [ Text Result: 0 ]

Example script to change password for an user:

# ========================================
# Purpose:
# Assigns the Password of a single AD user
# Returns:
# 0 for success
# Error text if unsuccessful
# Parameters:
# $serverName
# $serverDomain
# $personDN
# $userPassword (the password to assign to the personDN)
# Called from:
# (script) "Set AD Password"
# Author:
# John Munro (HJM) from Deutsche Schule Tokyo Yokohama
# Notes:
# none
# History:
# 2020-07-10 HJM - created
# 2021-05-20 HJM - Replaced bind code with call to LDAPServerBind (including added parameter $serverDomain to all calls)
# ========================================
#
Set Variable [ $! ; Value: #Assign ( Get ( ScriptParameter ) ) ]
#
# The branch in LDAP containing all active entries
Set Variable [ $searchBase ; Value: "ou=DSTY Groups,dc=dsty,dc=ac,dc=jp" ]
#
Set Error Capture [ On ]
#
# If debugging these parameters will be empty so fill with test data
If [ $serverName = "" ]
    Set Variable [ $serverName ; Value: "sys-dc1" ]
End If
If [ $serverName = "" ]
    Set Variable [ $serverDomain ; Value: "dsty.ac.jp" ]
End If
If [ $personDN = "" ]
    Set Variable [ $personDN ; Value: "CN=DySIS testUser,OU=VerwaltungOU,OU=DSTY Groups,DC=dsty,DC=ac,DC=jp" ]
End If
If [ $userPassword = "" ]
    Set Variable [ $userPassword ; Value: "Welcome" ]
End If
#
# Bind to LDAP
Perform Script [ Specified: From list ; “LDAPServerBind” ; Parameter: # ( "serverName" ; $serverName ) & # ( "serverDomain" ; $serverDomain ) ]
# Returns $error,$resultText, $ldap
#
Set Variable [ $! ; Value: #Assign ( Get ( ScriptResult ) ) ]
If [ $error <> 0 ]
    Go to Layout [ original layout ; Animation: None ]
    Show Custom Dialog [ "LDAP error" ; $resultText ]
    Exit Script [ Text Result: # ( "error" ; $error ) & # ( "resultText" ; "LDAP error: " & $resultText ) ]
End If
#
#
# Check the personDN is valid and update the dn to contain the targetOU
Set Variable [ $LDAPFilter ; Value: "" ]
Set Variable [ $result ; Value: MBS ( "LDAP.Search" ; $ldap ; $personDN ; "base" ; $LDAPFilter ; "" ; 0 ; 4 ; 1 ) ]
If [ MBS( "IsError" ) ]
    Set Variable [ $errorText ; Value: "Failed to locate the personDN." & ¶ & $personDN & ¶ & $result ]
    Show Custom Dialog [ "LDAP Error" ; $errorText ]
    # Cleanup
    Set Variable [ $releaseResult ; Value: MBS("LDAP.Release"; $ldap) ]
    Exit Script [ Text Result: "LDAP error. " & $errorText ]
End If
#
Set Variable [ $foundDN ; Value: MBS("LDAP.SearchResult.DistinguishedName"; $ldap; 0 ) ]
If [ $foundDN <> $personDN ]
    Set Variable [ $errorText ; Value: "The found record DN did not match personDN." & ¶ & "Found: " & $foundDN & ¶ & "PersonDN: " & $personDN & ¶ & $result ]
    Show Custom Dialog [ "LDAP Error" ; $errorText ]
    # Cleanup
    Set Variable [ $releaseResult ; Value: MBS("LDAP.Release"; $ldap) ]
    Exit Script [ Text Result: "LDAP error. " & $errorText ]
End If
#
# ===============================================================================================
# Set the password
#
# Add double quotes to the password passed as a parameter
Set Variable [ $encodedPW ; Value: "\"" & $userPassword & "\"" ]
# Change to 8 bit hex
Set Variable [ $encodedPW ; Value: HexEncode ( $encodedPW ) ]
# Change 8 bit hex to 16 bit hex
Set Variable [ $encodedPW ; Value: Hex8to16LE ( $encodedPW ) ]
#
# Build the JSON for the modify
Set Variable [ $json ; Value: "[{ \"operation\": \"Replace\", \"name\": \"unicodePwd\", \"hex\": true, \"value\": \"" & $encodedPW & "\" }]" ]
#
# Attempt to modify the password via the unicode attribute
Set Variable [ $result ; Value: MBS( "LDAP.ModifyJSON" ; $ldap ; $personDN ; $json ) ]
If [ MBS( "IsError" ) ]
    Set Variable [ $errorText ; Value: "Failed to set the password." & ¶ & $result & ¶ & $json ]
    Show Custom Dialog [ "LDAP Error" ; $errorText ]
    # Cleanup
    Set Variable [ $releaseResult ; Value: MBS("LDAP.Release"; $ldap) ]
    Exit Script [ Text Result: "LDAP error. " & $errorText ]
End If
#
#
# ===============================================================================================
# Require the password to be changed on the next login
#
Set Variable [ $pwdLastSet ; Value: "{ \"operation\": \"Replace\", \"name\": \"pwdLastSet\", \"value\": \"0\" }" ]
#
# Build the JSON for the modify
Set Variable [ $json ; Value: "[" & $pwdLastSet & "]" ]
#
# Attempt to modify the password via the unicode attribute
Set Variable [ $result ; Value: MBS( "LDAP.ModifyJSON" ; $ldap ; $personDN ; $json ) ]
If [ MBS( "IsError" ) ]
    Set Variable [ $errorText ; Value: "Failed to set 'User must change password at next logon'." & ¶ & $result & ¶ & $json ]
    Show Custom Dialog [ "LDAP Error" ; $errorText ]
    # Cleanup
    Set Variable [ $releaseResult ; Value: MBS("LDAP.Release"; $ldap) ]
    Exit Script [ Text Result: "LDAP error. " & $errorText ]
End If
#
#
# Cleanup
Set Variable [ $releaseResult ; Value: MBS("LDAP.Release"; $ldap) ]
Go to Layout [ original layout ; Animation: None ]
#
# Return error free result
Exit Script [ Text Result: 0 ]

Example script to set group for user:

# ========================================
# Purpose:
# Adds or removes membership in a AD Group of a single AD user
# Returns:
# $error = Error code if unsuccessful
# $error = 0 for success
# $resultText = Text summary of the success or error
# Parameters:
# $serverName
# $serverDomain
# $operation (ADD, DELETE)
# $personDN
# $groupName (base name only, excluding domain name)
# $groupDomain
# Called from:
# (script) "Toggle AD Group"
# Author:
# John Munro (HJM) from Deutsche Schule Tokyo Yokohama
# Notes:
# none
# History:
# 2020-06-19 HJM - created
# 2021-05-20 HJM - Replaced bind code with call to LDAPServerBind (including added parameter $serverDomain to all calls)
# 2021-05-21 HJM - modified result returned to be in #Assign variable method
# ========================================
#
Set Variable [ $! ; Value: #Assign ( Get ( ScriptParameter ) ) ]
#
# The branch in LDAP containing all active entries
Set Variable [ $searchBase ; Value: "dc=dsty,dc=ac,dc=jp" ]
#
Set Error Capture [ On ]
#
# If debugging these parameters will be empty so fill with test data
If [ $serverName = "" ]
    Set Variable [ $serverName ; Value: "sys-dc1" ]
End If
If [ $serverName = "" ]
    Set Variable [ $serverDomain ; Value: "dsty.ac.jp" ]
End If
If [ $operation = "" ]
    Set Variable [ $operation ; Value: "Add" ]
End If
If [ $personDN = "" ]
    Set Variable [ $personDN ; Value: "CN=John Munro,OU=SysAdmins,OU=VerwaltungOU,OU=DSTY Groups,DC=dsty,DC=ac,DC=jp" ]
End If
If [ $groupName = "" ]
    Set Variable [ $groupName ; Value: "IT-Admin-Staff" ]
End If
If [ $groupDomain = "" ]
    Set Variable [ $groupDomain ; Value: "dsty.ac.jp" ]
End If
#
#
# Bind to LDAP
Perform Script [ Specified: From list ; “LDAPServerBind” ; Parameter: # ( "serverName" ; $serverName ) & # ( "serverDomain" ; $serverDomain ) ]
# Returns $error,$resultText, $ldap
#
Set Variable [ $! ; Value: #Assign ( Get ( ScriptResult ) ) ]
If [ $error <> 0 ]
    Go to Layout [ original layout ; Animation: None ]
    Show Custom Dialog [ "LDAP error" ; $resultText ]
    Exit Script [ Text Result: # ( "error" ; $error ) & # ( "resultText" ; $resultText ) ]
End If
#
# Retreive the groupDN from the $groupName
Set Variable [ $LDAPFilter ; Value: "(&(objectClass=group)(sAMAccountName=" & $groupName & "))" ]
Set Variable [ $result ; Value: MBS ( "LDAP.Search" ; $ldap ; $searchBase ; "subtree" ; $LDAPFilter ; "" ; 0 ; 4 ; 99 ) ]
Set Variable [ $entryCount ; Value: MBS("LDAP.SearchResult.Count"; $ldap) ]
If [ $entryCount > 1 ]
    #
    # More than one group with the given name exists, there should only be one.
    Set Variable [ $error ; Value: 1 ]
    Set Variable [ $errorText ; Value: "More than 1 group found containing the name:" & ¶ & $groupName ]
    Show Custom Dialog [ "LDAP Error" ; $errorText ]
    # Cleanup
    Set Variable [ $releaseResult ; Value: MBS("LDAP.Release"; $ldap) ]
    Exit Script [ Text Result: # ( "error" ; $error ) & # ( "resultText" ; $errorText ) ]
    #
Else If [ $entryCount = 0 ]
    #
    # No such group found so create it
    #
    Set Variable [ $resultText ; Value: "No AD group found containing the name:" & ¶ & $groupName & ¶ & "OK to created it?" ]
    Show Custom Dialog [ "LDAP Warning" ; $resultText ]
    #
    If [ Get ( LastMessageChoice ) = 1 or PatternCount ( Get ( ApplicationVersion ) ; "Server" ) //script is running on server so create the group by default ]
        #
        # Create the new group
        Perform Script [ Specified: From list ; “Create AD Group (worker)” ; Parameter: # ( "serverName" ; $serverName ) & # ( "serverDomain" ; $serverDomain ) & # ( "baseOU" ; $searchBase ) & # ( "groupName" ; $groupName ) & # ( "groupDomain" ; $groupDomain ) ]
        #
        Set Variable [ $! ; Value: #Assign ( Get ( ScriptResult ) ) ]
        If [ $error <> 0 ]
            Show Custom Dialog [ "LDAP error" ; $resultText ]
            Set Variable [ $releaseResult ; Value: MBS("LDAP.Release"; $ldap) ]
            Go to Layout [ original layout ; Animation: None ]
            Exit Script [ Text Result: # ( "error" ; $error ) & # ( "resultText" ; "LDAP error: " & $resultText ) ]
        End If
        #
        Set Variable [ $warning ; Value: "New AD group: " & $groupName & " created at: " & $groupDN ]
        Set Variable [ $LDAPFilter ; Value: "(&(objectClass=group)(sAMAccountName=" & $groupName & "))" ]
        Set Variable [ $result ; Value: MBS ( "LDAP.Search" ; $ldap ; $searchBase ; "subtree" ; $LDAPFilter ; "" ; 0 ; 4 ; 99 ) ]
        #
    Else
        # Group creation not approved, so cannot proceed to add user to the group
        Set Variable [ $error ; Value: 2 ]
        Set Variable [ $errorText ; Value: "No AD group found containing the name:" & ¶ & $groupName & " and creation not approved by user" ]
        Show Custom Dialog [ "LDAP Error" ; $errorText ]
        # Cleanup
        Set Variable [ $releaseResult ; Value: MBS("LDAP.Release"; $ldap) ]
        Go to Layout [ original layout ; Animation: None ]
        Exit Script [ Text Result: # ( "error" ; $error ) & # ( "resultText" ; $errorText ) ]
    End If
End If
#
Set Variable [ $groupDN ; Value: MBS("LDAP.SearchResult.DistinguishedName"; $ldap; 0 ) ]
#
# Check the personDN is valid and add the personDN to the Group if so
Set Variable [ $LDAPFilter ; Value: "" ]
Set Variable [ $result ; Value: MBS ( "LDAP.Search" ; $ldap ; $personDN ; "base" ; $LDAPFilter ; "" ; 0 ; 4 ; 1 ) ]
If [ MBS("LDAP.SearchResult.DistinguishedName"; $ldap; 0 ) = $personDN ]
    #
    # Build the JSON for the modify
    Set Variable [ $json ; Value: "[{ \"operation\": \"" & $operation & "\", \"type\": \"member\", \"value\": \"" & $personDN & "\" }]" ]
    #
    # Attempt to modify the groupDN record
    Set Variable [ $result ; Value: MBS( "LDAP.ModifyJSON" ; $ldap ; $groupDN ; $json ) ]
    #
    If [ MBS( "IsError" ) ]
        Set Variable [ $error ; Value: 3 ]
        Set Variable [ $errorText ; Value: "Failed to modify the 'member' attribute of the Group record." & ¶ & $result ]
        Show Custom Dialog [ "LDAP Error" ; $errorText ]
        # Cleanup
        Set Variable [ $releaseResult ; Value: MBS("LDAP.Release"; $ldap) ]
        Exit Script [ Text Result: # ( "error" ; $error ) & # ( "resultText" ; $errorText ) ]
    End If
End If
#
# Cleanup
Set Variable [ $releaseResult ; Value: MBS("LDAP.Release"; $ldap) ]
Go to Layout [ original layout ; Animation: None ]
#
#
# Return error free result together with any non-fatal warnings if they exist
Exit Script [ Text Result: # ( "error" ; 0 ) & # ( "resultText" ; "Group set success. " & $warning ) ]

See also

Release notes

Example Databases

Blog Entries

This function checks for a license.

Created 15th December 2015, last changed 17th July 2022


LDAP.Rename - LDAP.SearchResult.AttributeCount