Solved

create login  and user programtically using SMO sql 008

Posted on 2011-09-13
1
395 Views
Last Modified: 2012-06-27
How can I create login and user using SMO in sql 2008
I would like to create a program that creates login and user programtcally using SMO
if the login already exists ithen only create a user and give read only access to user
otherwise create new log and user and give the read only access to the dataabse

how can I do this using SMO sql 2008?
0
Comment
Question by:jung1975
1 Comment
 
LVL 24

Accepted Solution

by:
DBAduck - Ben Miller earned 500 total points
ID: 36536564
To create a login, you can see how to create it on http://powershellfordbas.com.  This is a generic creation, but you can also find out if it exists, by creating a server and checking the logins.



   
$server = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server -ArgumentList "servername"
$database = $server.Databases["databasename"]
if($server.Logins["loginname"] -eq $null) {
   $login = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Login -ArgumentList "servername", "loginname"
   $login.LoginType = "LoginType"  # SqlLogin, WindowsUser, WindowsGroup, Certificate, AssymetricKey
   $login.Create("Password")
}
else {
   $login = $server.Logins["loginname"]
}

$user = New-Object -TypeName Microsoft.SqlServer.Management.Smo.User -ArgumentList $database, "Username"
$user.Login = $login.Name
$user.AddToRole("db_datareader")
$user.Create()

Open in new window

0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
PROPERCASE SCRIPT IN SQL 3 23
Sql query with where clause 2 45
partitioning database after decade growth 8 60
Estimating my database size 7 17
INTRODUCTION: While tying your database objects into builds and your enterprise source control system takes a third-party product (like Visual Studio Database Edition or Red-Gate's SQL Source Control), you can achieve some protection using a sing…
If you have heard of RFC822 date formats, they can be quite a challenge in SQL Server. RFC822 is an Internet standard format for email message headers, including all dates within those headers. The RFC822 protocols are available in detail at:   ht…
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…

726 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question