Impersonate and Elevate via Server Script
Back to more incredibly useful undocumented APIs in ServiceNow… being able to impersonate a user and elevate to security admin to perform restricted actions via a script.
How To
Impersonate
gs.getSession().impersonate('sys_id_of_user');
Elevate
GlideSecurityManager.get().enableElevatedRole('security_admin');
Impersonate back
The trick here is to store the original user id before you impersonate if you want to impersonate back
var originalID = gs.getUserID();
gs.getSession().impersonate('sys_id_of_user');
gs.getSession().impersonate(originalID); //impersonate back
Example Use Cases
There are quite a number of reasons you might want to impersonate or elevate.
Impersonate
Approve on behalf of another user
Activity log, comments, and work notes showing as an automation user
Elevate
Grant admin roles to user accounts automatically via a script
Grant yourself snc_read_only
Modify ACLs via a script
PS. Impersonations are tracked in the system logs, in case someone may be up to something, always good to check there.