Book Image

SQL Server 2014 with PowerShell v5 Cookbook

By : Donabel Santos
Book Image

SQL Server 2014 with PowerShell v5 Cookbook

By: Donabel Santos

Overview of this book

Table of Contents (21 chapters)
SQL Server 2014 with PowerShell v5 Cookbook
Credits
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Preface
Index

Creating a database user


This recipe shows 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. Alternatively, feel free to substitute this with a login that already exists in your system.

In our recipe, we will use a login called eric, which we will map to a user called eric in the AdventureWorks2014 database. Here's the T-SQL equivalent of what we are trying to accomplish:

USE [AdventureWorks2014]
GO

CREATE USER [eric]
FOR LOGIN [eric]

How to do it...

Here are the steps to create a database user:

  1. Open PowerShell ISE as an administrator.

  2. 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 = "localhost"
    $server = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server -ArgumentList $instanceName
  3. Add the following script and run:

    $loginName ...