This is the legacy documentation for Google Ads scripts. Go to the current docs.

Ads Manager Scripts

Stay organized with collections Save and categorize content based on your preferences.

Get all accounts

function getAllAccounts() {
  var accountIterator = AdsManagerApp.accounts().get();

  while (accountIterator.hasNext()) {
    var account = accountIterator.next();
    var accountName = account.getName() ? account.getName() : '--';
    Logger.log('%s,%s,%s,%s', account.getCustomerId(), accountName,
        account.getTimeZone(), account.getCurrencyCode());
  }
}

Get accounts from customer IDs

function getAccountsFromCustomerIds() {
  // This is useful when you are reading customer IDs from an external data
  // source, such as a Google Spreadsheet.

  // You can also use the condition "CustomerId in ['123-456-7890',
  // '345-678-9000', '890-123-6000']".
  var accountIterator = AdsManagerApp.accounts()
      .withIds(['123-456-7890', '345-678-9000', '890-123-6000'])
      .get();

  while (accountIterator.hasNext()) {
    var account = accountIterator.next();
    var accountName = account.getName() ? account.getName() : '--';
    Logger.log('%s,%s,%s,%s', account.getCustomerId(), accountName,
        account.getTimeZone(), account.getCurrencyCode());
  }
}

Get accounts by label

function getAccountsByLabel() {
  // Only CONTAINS and DOES_NOT_CONTAIN operators are supported.
  var accountIterator = AdsManagerApp.accounts()
      .withCondition("LabelNames CONTAINS 'High spend accounts'")
      .get();

  while (accountIterator.hasNext()) {
    var account = accountIterator.next();
    var accountName = account.getName() ? account.getName() : '--';
    Logger.log('%s,%s,%s,%s', account.getCustomerId(), accountName,
        account.getTimeZone(), account.getCurrencyCode());
  }
}

Get accounts by stats

function getAccountByStats() {
  // This is useful when you need to identify accounts that were performing
  // well (or poorly) in a given time frame.

  var accountIterator = AdsManagerApp.accounts()
      .withCondition('Clicks > 10')
      .forDateRange('LAST_MONTH')
      .orderBy('Clicks DESC')
      .get();

  while (accountIterator.hasNext()) {
    var account = accountIterator.next();
    var stats = account.getStatsFor('LAST_MONTH');
    Logger.log('%s,%s,%s', account.getCustomerId(),
        stats.getClicks().toFixed(0), stats.getImpressions().toFixed(0));
  }
}

Get accounts under a child account

function getAccountsUnderAChildManagerAccount() {
  // This is useful if you want to restrict your script to process only accounts
  // under a specific child manager account. This allows you to manage specific
  // child manager account hierarchies from the top-level manager account
  // without having to duplicate your script in the child manager account.

  var accountIterator = AdsManagerApp.accounts()
      .withCondition("ManagerCustomerId = '1234567890'")
      .get();

  while (accountIterator.hasNext()) {
    var account = accountIterator.next();
    var accountName = account.getName() ? account.getName() : '--';
    Logger.log('%s,%s,%s,%s', account.getCustomerId(), accountName,
        account.getTimeZone(), account.getCurrencyCode());
  }
}

Update multiple accounts in series

function updateAccountsInSeries() {
  // You can use this approach when you have only minimal processing to
  // perform in each of your client accounts.

  // Select the accounts to be processed.
  var accountIterator = AdsManagerApp.accounts()
      .withCondition("LabelNames CONTAINS 'Cars'")
      .get();

  // Save the manager account, to switch back later.
  var managerAccount = AdsApp.currentAccount();

  while (accountIterator.hasNext()) {
    var account = accountIterator.next();

    // Switch to the account you want to process.
    AdsManagerApp.select(account);

    // Retrieve all campaigns to be paused.
    var campaignIterator = AdsApp.campaigns()
        .withCondition("LabelNames = 'Christmas promotion'")
        .get();

    while (campaignIterator.hasNext()) {
      var campaign = campaignIterator.next();
      Logger.log('Pausing campaign %s in account %s', campaign.getName(),
          account.getCustomerId());
      campaign.pause();
    }
  }
}

Update multiple accounts in parallel

function updateAccountsInParallel() {
  // You can use this approach when you have a large amount of processing
  // to do in each of your client accounts.

  // Select the accounts to be processed. You can process up to 50 accounts.
  var accountSelector = AdsManagerApp.accounts()
      .withCondition("LabelNames CONTAINS 'High spend accounts'")
      .withLimit(50);

  // Process the account in parallel. The callback method is optional.
  accountSelector.executeInParallel('processAccount', 'allFinished');
}

/**
 * Process one account at a time. This method is called by the executeInParallel
 * method call in updateAccountsInParallel function for every account that
 * it processes.
 *
 * @return {Number} the number of campaigns paused by this method.
 */
function processAccount() {
  // executeInParallel will automatically switch context to the account being
  // processed, so all calls to AdsApp will apply to the selected account.
  var account = AdsApp.currentAccount();
  var campaignIterator = AdsApp.campaigns()
      .withCondition("LabelNames = 'Christmas promotion'")
      .get();

  while (campaignIterator.hasNext()) {
    var campaign = campaignIterator.next();
    Logger.log('Pausing campaign %s in account %s', campaign.getName(),
        account.getCustomerId());
    campaign.pause();
  }
  // Optional: return a string value. If you have a more complex JavaScript
  // object to return from this method, use JSON.stringify(value). This value
  // will be passed on to the callback method, if specified, in the
  // executeInParallel method call.
  return campaignIterator.totalNumEntities().toFixed(0);
}

/**
 * Post-process the results from processAccount. This method will be called
 * once all the accounts have been processed by the executeInParallel method
 * call.
 *
 * @param {Array.<ExecutionResult>} results An array of ExecutionResult objects,
 * one for each account that was processed by the executeInParallel method.
 */
function allFinished(results) {
  for (var i = 0; i < results.length; i++) {
    // Get the ExecutionResult for an account.
    var result = results[i];

    Logger.log('Customer ID: %s; status = %s.', result.getCustomerId(),
        result.getStatus());

    // Check the execution status. This can be one of ERROR, OK, or TIMEOUT.
    if (result.getStatus() == 'ERROR') {
      Logger.log("-- Failed with error: '%s'.", result.getError());
    } else if (result.getStatus() == 'OK') {
      // This is the value you returned from processAccount method. If you
      // used JSON.stringify(value) in processAccount, you can use
      // JSON.parse(text) to reconstruct the JavaScript object.
      var retval = result.getReturnValue();
      Logger.log('--Processed %s campaigns.', retval);
    } else {
      // Handle timeouts here.
    }
  }
}