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 login


This recipe shows how you can create a SQL login using PowerShell and SMO.

Getting ready

For this recipe, we will create a SQL login called eric. Here's the T-SQL equivalent of what we are trying to accomplish:

CREATE LOGIN [eric]
WITH PASSWORD=N'YourSuperStrongPassword',
CHECK_EXPIRATION=OFF
GO

How to do it...

These are the steps to create a login:

  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 = "eric"
    
    #for our recipe
    #drop login if it exists
    if ($server.Logins.Contains($loginName))
    {
       $server.Logins[$loginName].Drop()
    }
    
    $login = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Login -ArgumentList $server, $loginName
    
    #specify SQL...