Stay organized with collections
Save and categorize content based on your preferences.
The Admin SDK Reports service allows you to use the Admin SDK's
Reports API in
Apps Script. This API gives administrators
of Google Workspace domains (including resellers) the
ability to create custom usage reports for their domain.
Reference
For detailed information on this service, see the
reference documentation for the Admin SDK
Reports API. Like all advanced services in Apps Script, the Admin SDK Reports
service uses the same objects, methods, and parameters as the public API. For more information, see How method signatures are determined.
/** * Generates a login activity report for the last week as a spreadsheet. The * report includes the time, user, and login result. * @see https://developers.google.com/admin-sdk/reports/reference/rest/v1/activities/list */functiongenerateLoginActivityReport(){constnow=newDate();constoneWeekAgo=newDate(now.getTime()-7*24*60*60*1000);conststartTime=oneWeekAgo.toISOString();constendTime=now.toISOString();constrows=[];letpageToken;letpage;do{page=AdminReports.Activities.list('all','login',{startTime:startTime,endTime:endTime,maxResults:500,pageToken:pageToken});constitems=page.items;if(items){for(constitemofitems){constrow=[newDate(item.id.time),item.actor.email,item.events[0].name];rows.push(row);}}pageToken=page.nextPageToken;}while(pageToken);if(rows.length===0){console.log('Noresultsreturned.');return;}constspreadsheet=SpreadsheetApp.create('GoogleWorkspaceLoginReport');constsheet=spreadsheet.getActiveSheet();// Append the headers.constheaders=['Time','User','LoginResult'];sheet.appendRow(headers);// Append the results.sheet.getRange(2,1,rows.length,headers.length).setValues(rows);console.log('Reportspreadsheetcreated:%s',spreadsheet.getUrl());}
Generate user usage report
This sample generates a user usage report for this day last week as a
spreadsheet. The report includes the date, user, last login time, number of
emails received, and number of docs owned.
/** * Generates a user usage report for this day last week as a spreadsheet. The * report includes the date, user, last login time, number of emails received, * and number of drive files created. * @see https://developers.google.com/admin-sdk/reports/reference/rest/v1/userUsageReport/get */functiongenerateUserUsageReport(){consttoday=newDate();constoneWeekAgo=newDate(today.getTime()-7*24*60*60*1000);consttimezone=Session.getScriptTimeZone();constdate=Utilities.formatDate(oneWeekAgo,timezone,'yyyy-MM-dd');constparameters=['accounts:last_login_time','gmail:num_emails_received','drive:num_items_created'];constrows=[];letpageToken;letpage;do{page=AdminReports.UserUsageReport.get('all',date,{parameters:parameters.join(','),maxResults:500,pageToken:pageToken});if(page.warnings){for(constwarningofpage.warnings){console.log(warning.message);}}constreports=page.usageReports;if(reports){for(constreportofreports){constparameterValues=getParameterValues(report.parameters);constrow=[report.date,report.entity.userEmail,parameterValues['accounts:last_login_time'],parameterValues['gmail:num_emails_received'],parameterValues['drive:num_items_created']];rows.push(row);}}pageToken=page.nextPageToken;}while(pageToken);if(rows.length===0){console.log('Noresultsreturned.');return;}constspreadsheet=SpreadsheetApp.create('GoogleWorkspaceUserUsageReport');constsheet=spreadsheet.getActiveSheet();// Append the headers.constheaders=['Date','User','LastLogin','NumEmailsReceived','NumDriveFilesCreated'];sheet.appendRow(headers);// Append the results.sheet.getRange(2,1,rows.length,headers.length).setValues(rows);console.log('Reportspreadsheetcreated:%s',spreadsheet.getUrl());}/** * Gets a map of parameter names to values from an array of parameter objects. * @param {Array} parameters An array of parameter objects. * @return {Object} A map from parameter names to their values. */functiongetParameterValues(parameters){returnparameters.reduce((result,parameter)=>{constname=parameter.name;letvalue;if(parameter.intValue!==undefined){value=parameter.intValue;}elseif(parameter.stringValue!==undefined){value=parameter.stringValue;}elseif(parameter.datetimeValue!==undefined){value=newDate(parameter.datetimeValue);}elseif(parameter.boolValue!==undefined){value=parameter.boolValue;}result[name]=value;returnresult;},{});}
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Missing the information I need","missingTheInformationINeed","thumb-down"],["Too complicated / too many steps","tooComplicatedTooManySteps","thumb-down"],["Out of date","outOfDate","thumb-down"],["Samples / code issue","samplesCodeIssue","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2024-12-19 UTC."],[[["The Admin SDK Reports service enables Google Workspace administrators to create custom usage reports within Apps Script, using the Admin SDK's Reports API."],["This advanced service requires prior enabling and mirrors the functionalities of the public API, using the same objects, methods, and parameters."],["Sample code is provided demonstrating how to generate login activity reports (including time, user, and login result) and user usage reports (including date, user, last login, emails received, and docs created) for a specified timeframe, outputting the data into a spreadsheet."],["Comprehensive reference documentation and a support guide for the Admin SDK Reports API are available for further information and assistance."]]],[]]