Solved

create login  and user programtically using SMO sql 008

Posted on 2011-09-13
1
385 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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Naughty Me. While I was changing the database name from DB1 to DB_PROD1 (yep it's not real database name ^v^), I changed the database name and notified my application fellows that I did it. They turn on the application, and everything is working. A …
This article explains how to reset the password of the sa account on a Microsoft SQL Server.  The steps in this article work in SQL 2005, 2008, 2008 R2, 2012, 2014 and 2016.
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …
This tutorial demonstrates a quick way of adding group price to multiple Magento products.

743 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now