google-admin-sdkgoogle-admin-settings-api

Update addresses for Google users via apps script


I have written a small script with which I can assign a new work address to a Google user via Google Apps Script. The script also runs without errors and if a value is already stored in the field for the work address, it is also deleted, but the new address is not transferred to the field and saved.

The values that are to be entered are also pulled from my GSheet without any problems.

When I check the field via the Google API checker, no values are stored after executing my script - before that they were.

Who has a tip for me as to where my error is?

Thanks in advance.

function myEditUserDatas() {
  var ssID = "1_yDRkyO9kwT-EPGLqJf99KBAb2-xxxx-xx-x-xx---xx";
  var sheet = SpreadsheetApp.openById(ssID).getSheetByName("EditEmployees ");
  var myLR = sheet.getLastRow();

  for (let i = 2; i <= myLR; i++) {
    var uMail = sheet.getRange(i,2).getValue();
    var user = AdminDirectory.Users.get(uMail);

    var CompanyAddress = sheet.getRange(i,18).getValue();
    user.addresses = [
      {streetAddress: 'Neue Straße 123',
        city: 'Musterstadt',
        region: 'BY',
        postalCode: '12345',
        country: 'Deutschland',
        type: 'work'}
    ];

    AdminDirectory.Users.update(user, uMail);
  }
}

Solution

  • Update addresses for Google users

    Your code is almost there, when I tried and checked it on the API CHECKER the data is posted, see the sample output below:


    Sample Output1


    To get the data work I added some line of code to the code given.

    function myEditUserDatas() {
      var ssID = '--Sheet ID--';
      var sheet = SpreadsheetApp.openById(ssID).getSheetByName("--Sheet Name--");
      var myLR = sheet.getLastRow();
    
      for (let i = 2; i <= myLR; i++) {
        var uMail = sheet.getRange(i, 2).getValue();
        var user = AdminDirectory.Users.get(uMail);
    
        // var CompanyAddress = sheet.getRange(i,18).getValue();
        user.addresses = [
          {
            streetAddress: 'Neue Straße 123',
            city: 'Musterstadt',
            region: 'BY',
            postalCode: '12345',
            country: 'Deutschland',
            type: 'work'
          }
        ];
        
    
        // Use the formatted Method here.
        user.addresses[0].formatted = `${user.addresses[0].streetAddress}, ${user.addresses[0].city}, ${user.addresses[0].region}, ${user.addresses[0].postalCode}, ${user.addresses[0].country}, ${user.addresses[0].type}`;
        AdminDirectory.Users.update(user, uMail);
      }
    }
    

    Sample Output:

    enter image description here

    The Data is also reflected in Admin Console in User Information.


    enter image description here

    Reference:

    formatted Image