I have a Powershell script that executes in the context of a Windows user. This user has a login on a SQL 2012 instance that is a member of the sysadmin server role.
I want the script to add another login on the SQL instance (which also has a corresponding Windows user) to the sysadmin server role.
To try this out in Management Studio (connected as SA), I'm using the following script:
execute as user = 'domain\currentsysadmin'
IF IS_SRVROLEMEMBER('sysadmin', 'domain\futuresysadmin') != 1
ALTER SERVER ROLE [sysadmin] ADD MEMBER [domain\futuresysadmin]
revert
I have two issues here:
When I run the script as it's displayed here, the call to IS_SRVROLEMEMBER returns 0 as expected, but even though the domain\currentsysadmin login is a member of sysadmin, the call to ALTER SERVER ROLE returns:
Msg 15151, Level 16, State 1, Line 8 Cannot alter the server role 'sysadmin', because it does not exist or you do not have permission.
When I run this in the context of SA without the EXECUTE AS statement, the ALTER SERVER ROLE statement appears to run successfully, but when I check the domain\futuresysadmin login, it is still not a member of the sysadmin role
How can I add the domain\futuresystem login to the sysadmin server role?
Use sp_addsrvrolemember
:
EXEC master..sp_addsrvrolemember @loginame = N'domain\futuresysadmin', @rolename = N'sysadmin'
UPDATE: User context switching doesn't inherit any server roles, like sysadmin. In reading the documentation: "Server-level permissions granted explicitly to identities in the user token or through role memberships are not honored." When you switch user context, your user no longer has the right to grant sysadmin to another user.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With