Reputation: 31
Wondering if anyone has experience exporting a list of GA accounts and properties to a spreadsheet using the new Analytics Admin API.
I've used the Management API for this purpose in the past but that limits us to UA properties and I want to hopefully include GA4 properties here as well.
I've taken a shot at converting an old script to the new API but I haven't even succeeded in pulling in account names.
function listGA4Accounts() {
var createss = SpreadsheetApp.create("Google Analytics Accounts");
var ssid = createss.getId();
var openss = SpreadsheetApp.openById(ssid);
var insertsheet = openss.insertSheet('Google Analytics Schema');
insertsheet.setFrozenRows(1);
insertsheet.getRange("A1:D1").setValues([['displayName', 'Account ID', 'Property Name', 'Property ID']]);
var sheet = SpreadsheetApp.openById(createss.getId()).getSheetByName("Google Analytics Schema")
var accounts = AnalyticsAdmin.Accounts.list();
if (accounts && !accounts.error) {
accounts = accounts.accounts;
// Logger.log(accounts[0]);
for (var i = 0, account; account = accounts[i]; i++) {
sheet.appendRow([accounts.accounts[i].displayName]);
}
}
}
Upvotes: 3
Views: 2932
Reputation: 71
I've been struggling with this as well. Here's what I came up with after a lot of trail and error:
function listAccounts() {
try {
accounts = AnalyticsAdmin.AccountSummaries.list();
//Logger.log(accounts);
if (!accounts.accountSummaries || !accounts.accountSummaries.length) {
Logger.log('No accounts found.');
return;
}
Logger.log(accounts.accountSummaries.length + ' accounts found');
for (let i = 0; i < accounts.accountSummaries.length; i++) {
const account = accounts.accountSummaries[i];
Logger.log('** Account: name "%s", displayName "%s".', account.name, account.displayName);
if (account.propertySummaries) {
properties = AnalyticsAdmin.Properties.list({filter: 'parent:' + account.account});
if (properties.properties !== null) {
for (let j = 0 ; j < properties.properties.length ; j++) {
var propertyID = properties.properties[j].name.replace('properties/','');
Logger.log("GA4 Property: " + properties.properties[j].displayName + '(' + propertyID + ')')
}
}
} else {
var accountID = account.account.replace('accounts/','');
var webProperties = Analytics.Management.Webproperties.list(accountID);
for (var j = 0; j < webProperties.items.length; j++) {
Logger.log("UA Property: " + webProperties.items[j].name + '(' + webProperties.items[j].id + ')');
var profiles = Analytics.Management.Profiles.list(accountID, webProperties.items[j].id);
for (var k = 0; k < profiles.items.length; k++) {
Logger.log('Profile:' + profiles.items[k].name);
}
}
}
}
} catch (e) {
// TODO (Developer) - Handle exception
Logger.log('Failed with error: %s', e.error);
}
}
Not saying it's the right way...but it does appear to be able to pull all of my UA and GA4 properties.
If you only want GA4 properties then you can leave out the else on "if (account.propertySummaries)".
Upvotes: 2