Creating a database user
This recipe demonstrates how to create a database user by using PowerShell and SMO.
Getting ready
If you haven't already done so in the Creating a login recipe, create a SQL login called eric
.
In our recipe, we will
use a login called eric
, which we will map to a user called eric
in the AdventureWorks2008R2
database. The T-SQL equivalent of what we are trying to accomplish is:
USE [AdventureWorks2008R2] GO CREATE USER [eric] FOR LOGIN [eric]
How to do it...
Here are the steps for creating a database user:
Open the PowerShell console by going to Start | Accessories | Windows PowerShell | Windows PowerShell ISE.
Import the
SQLPS
module and create a new SMO Server object as follows:#import SQL Server module Import-Module SQLPS -DisableNameChecking #replace this with your instance name $instanceName = "KERRIGAN" $server = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server -ArgumentList $instanceName
Add the following script and run it:
$loginName = "eric" #get...