Add User to SQL Server Database Role with PowerShell and Quickly Creating Test Users

There is a newer up to date version of this post here using the dbatools module and the sqlserver module


But if you want to continue with this way read on!!

Having created Windows Users or SQL Users using the last two days posts, today we shall add them to a role on a database.

As I discussed previously I believe that to follow good practice I try to ensure that database permissions are granted by role membership and each role is created with the minimum amount of permissions required for successful execution of the task involved.

So with each database having the correct roles created and the users created we just need to add the user to the database and to the role. This is easily done with PowerShell.


The Add-UserToRole function takes four parameters Server,Database,User and Role and does a series of error checks.

With these functions you can easily create a number of Users and add them to database roles quickly and easily and repeatedly.

If the test team come to you and require 10 Test Users and 3 Test Administrators adding to the test database. I create 2 notepad files

image  image

and use them with the Add-SQLAccountToSQLRole and Add-UserToRole functions to create the users


Here are the results in PowerShell


and in SSMS


The Code is here


3 thoughts on “Add User to SQL Server Database Role with PowerShell and Quickly Creating Test Users

  1. Pingback: Create SQL Logins and add SQL Roles | A Power Knight's journey

  2. Pingback: Quickly Creating Test Users in SQL Server with PowerShell using the sqlserver module and dbatools | SQL DBA with A Beard

  3. Pingback: Create SQL logins and add SQL Database roles – A Power Knight's journey

Please feel free to comment on this post. All comments are moderated first before appearing on the site

This site uses Akismet to reduce spam. Learn how your comment data is processed.