getEditors方法仅返回部分用户,如何获取完整授权用户列表?
问题:Google Sheets脚本获取编辑器列表遗漏企业域名用户
我有一个允许多用户访问的电子表格,出于安全管理需求,需要通过邮件发送月度授权账户列表,但当前运行的脚本只能获取部分用户,遗漏了使用公司企业域名的成员。用个人账号(非公司域名)授权执行代码能拿到完整的用户列表,怀疑是权限范围相关问题导致。
当前使用的代码:
const editorsSprTR = SpreadsheetApp.openById(UNITED_MASTER_ID).getEditors(); const totalTREditors = editorsSprTR.length; var editorsTRStr = '(1) List of users:' + totalTREditors + 'persons\n' for (let i in editorsSprTR){ let email = editorsSprTR[i]; var editorsTRStr = editorsTRStr + ' ・' + email + '\n'; }
原因分析
企业域名账号运行脚本时,getEditors()方法仅能返回当前账号有权限查看的直接添加编辑器。如果企业域内用户的编辑权限是通过Google Workspace组授予的,或者运行脚本的账号本身没有查看所有域内用户权限的权限,就会出现用户遗漏的情况。而个人账号如果是表格所有者或拥有超级权限,则能获取所有直接/间接授权的用户。
解决方案
1. 替换getEditors()为getAllEditors()
getAllEditors()会返回所有拥有编辑权限的用户,包括通过组继承权限的成员,能覆盖更多场景。修改代码第一行即可:
const editorsSprTR = SpreadsheetApp.openById(UNITED_MASTER_ID).getAllEditors();
2. 确保运行账号的权限足够
让运行脚本的公司域名账号拥有表格的所有者权限或Google Workspace的超级管理员权限,这样才能获取所有域内用户的权限信息。普通编辑者权限可能无法查看全部授权用户。
3. 处理通过组授权的情况
如果部分用户是通过Google Workspace组获得编辑权限,getAllEditors()可能只返回组邮箱而非组内成员。这种情况需要结合Admin SDK获取组成员:
// 先在脚本编辑器的「服务」中启用Admin SDK function getGroupMembers(groupEmail) { const memberList = AdminDirectory.Members.list(groupEmail); return memberList.members ? memberList.members.map(item => item.email) : []; } // 主逻辑中处理组和单个用户 const editorsSprTR = SpreadsheetApp.openById(UNITED_MASTER_ID).getAllEditors(); const allEditors = []; editorsSprTR.forEach(editor => { const email = editor.getEmail(); // 判断是否为企业组(可根据实际域名调整) if (email.endsWith('@yourcompany.com') && isGroup(email)) { allEditors.push(...getGroupMembers(email)); } else { allEditors.push(email); } }); // 辅助函数:验证邮箱是否为Google Workspace组 function isGroup(email) { try { AdminDirectory.Groups.get(email); return true; } catch (error) { return false; } }
注意:使用Admin SDK需要运行账号拥有Google Workspace的组管理权限。
内容的提问来源于stack exchange,提问作者Wataru
相关产品推荐
相关产品推荐

