Search code examples
google-apps-scriptgoogle-admin-sdk

Is there a way to delete user.organizations[1] in Google Admin Console?


Making a script to create uniform gmail signatures and I noticed only a few users, out of the hundreds, have both user.organizations[0] and user.organizations[1]. This of course is bothering me terribly. I see on these users that the 1 is the primary and visible in GAC while the rest of the users that is the 0 that is visible. Is there a way to delete the extra organizations inside a user?


Solution

  • Yes, this is possible and it is very simple.

    We will need to use 2 methods:

    Steps:

    1. Feel free to use the API Explorer available in the documentation above to test these API calls.
    2. Use the Users.get method to obtain the data of the user you are interested in updating. You can make the result shorter by specifying a value in the fields parameter like so:
    "fields": "primaryEmail,organizations"
    
    1. This will return the data of the user including their primary email and a list of the organization(s) the user has.
    {
      "primaryEmail": "user@domain.com",
      "organizations": [
        {
          "title": "Accountant",
          "primary": true,
          "customType": "",
          "department": "Accounting",
          "description": "Full Time accountant",
          "costCenter": "CompanyTotalPro"
        },
        {
          "title": "Accountant",
          "primary": false,
          "customType": "",
          "department": "Accounting",
          "description": "Part Time accountant",
          "costCenter": "SecondaryCompany"
        }
      ]
    }
    
    1. This response will contain the data of one or more organizations, you will only need to copy the value you want to maintain and make an API call using the Users.update method. Like so:

    Don't worry about the code. What you need to see is that we are essentially obtaining the list of organizations and removing the one we don't want, and using the new set of information to overwrite the old one. Use this for reference.

    gapi.client.directory.users.update({
      "userKey": "user@domain.com",
      "resource": {
        "organizations": [
          {
            "title": "Accountant",
            "primary": true,
            "customType": "",
            "department": "Accounting",
            "description": "Full Time accountant",
            "costCenter": "CompanyTotalPro"
          }
        ]
      }
    })
    

    Use null to clear the value.

    "organizations": null