我正在使用Google Apps脚本在我们的谷歌应用程序中编写所有超级管理员和委派管理员的列表。
我的脚本工作正常,但它将结果限制为500个用户,因为谷歌有限制,谷歌建议使用pageToken,但不知道如何使用。
任何人都可以帮我理解如何在以下脚本中使用PageToken:
function getAdmins(){
var fileArray = [["First Name", "Last Name", "Email", "Admin Role"]]
var optionalArgs = {"customer":"my_customer", maxResults: 500}
var allUsers = AdminDirectory.Users.list(optionalArgs).users
for (i=0; i<allUsers.length; i++){
userDetails = allUsers[i]
var fName = userDetails.name.givenName
var lName = userDetails.name.familyName
var pEmail = userDetails.primaryEmail
var Admin = userDetails.isAdmin
var dAdmin = userDetails.isDelegatedAdmin
if (Admin === true) {
Admin = "Super Administrator"
}
else if (dAdmin === true){
Admin = "Delegated Administrator"
}
Logger.log(Admin)
}
var ss = SpreadsheetApp.getActive()
var sheet = ss.getSheetByName("Admin Users")
fileArray.push([fName, lName, pEmail,Admin]);
Logger.log(fileArray)
sheet.getRange(1, 1, fileArray.length, 4).setValues(fileArray)
}}
答案 0 :(得分:2)
要理解pageToken,您需要了解(或来自)
的返回值 AdminDirectory.Users.list(optionalArgs)
此函数返回reponse of the format:
{
"kind": "admin#directory#users",
"etag": etag,
"users": [
users Resource
],
"nextPageToken": string
}
要访问用户信息,请使用“用户”键,如此
var allUsers = AdminDirectory.Users.list(optionalArgs).users
//below the same is written in two seperate lines
var page = AdminDirectory.Users.list(optionalArgs)
var allUsers = page.users
从响应对象中可以看到,你还有nextPageToken键,它定义了响应中的下一页是什么,你就像这样抓住nextPageToken:
pageToken = page.nextPageToken;
然后你将pageToken传递给对AdminDirectory的新调用,如下所示:
var optionalArgs = {"customer":"my_customer", maxResults: 500, pageToken: pageToken}
page = AdminDirectory.Users.list(optionalArgs)
这将检索搜索的下一页以及搜索下一页的nextPageToken(如果有)。你进行递归调用,直到你不再有pageToken。
下面的代码应该完全相同,并且是通过合并来自example code on google developer page的代码和上面由@GlodyArora编写的代码来实现的。字面上只是添加了一个do while循环,如示例代码中所述。
function getAdmins(){
var fileArray = [["First Name", "Last Name", "Email", "Admin Role"]]
var pageToken, page;
do {
var optionalArgs = {"customer":"my_customer", maxResults: 500, pageToken: pageToken}
page = AdminDirectory.Users.list(optionalArgs)
var allUsers = page.users
for (i=0; i<allUsers.length; i++){
userDetails = allUsers[i]
var fName = userDetails.name.givenName
var lName = userDetails.name.familyName
var pEmail = userDetails.primaryEmail
var Admin = userDetails.isAdmin
var dAdmin = userDetails.isDelegatedAdmin
if (Admin === true) {
Admin = "Super Administrator"
}else if (dAdmin === true){
Admin = "Delegated Administrator"
}
Logger.log(Admin)
var ss = SpreadsheetApp.getActive()
var sheet = ss.getSheetByName("Admin Users")
fileArray.push([fName, lName, pEmail,Admin]);
}
pageToken = page.nextPageToken;
}
while(pageToken);
Logger.log(fileArray)
sheet.getRange(1, 1, fileArray.length, 4).setValues(fileArray)
}
希望它有助于澄清事情!