AppleScript to compare contacts in two groups and remove duplicate from one group

applescriptcontactsgroup

I want to create an AppleScript for Apple's Address Book (Contacts) app that will look at two Groups, and if a contact is in one Group, it will remove it from the other Group.

Specifically, I add potential clients to my Address Book so I can color-code their messages in Mail.app. They are added to a "Work – Pending" group. Once the project goes forward, I add them to a "Work – Current" group. The AppleScript would compare the two, look for duplicates and remove them from the 'Pending' group.

Best Answer

Here is a script written quickly. Should work. But I have not revised it down to be efficient.

tell application "Contacts"

    (*get the names of all groups *)
    set theGroupNames to name of groups

    (*choose you current group, the one to keep entries*)
    set text_returnedCurrent to choose from list theGroupNames with prompt "Choose Current Group" default items "Work - Current" without multiple selections allowed

    (*choose you pending group, the one to remove entries*)
    set text_returnedPending to choose from list theGroupNames with prompt "Choose Pending Group" default items "Work - Pending" without multiple selections allowed
    (*Get the people/entries of the Current group*)
    set the_peopleCurrent to people of group (text_returnedCurrent as text)

    (*Get the people/entries of the Pending group*)
    set the_peoplePending to people of group (text_returnedPending as text)

    (*iterate through the people of the Current group*)
    repeat with i from 1 to number of items in the_peopleCurrent

        (*get a person from the  Current group*)
        set thisPersonCurrent to item i of the_peopleCurrent

        (*iterate through ALL the people of the Pending group**)
        repeat with x from 1 to number of items in the_peoplePending

            (*get a person from the  Pending group*)
            set thisPersonPending to item x of the_peoplePending

            (*Check if the person from the Current group is the same person as thisPersonPending*)
            if thisPersonCurrent is equal to thisPersonPending then
                (* if they are remove them.  *)
                remove thisPersonPending from group (text_returnedPending as text)

                (*save the contacts changes*)
                save

            end if
        end repeat

    end repeat

end tell