Book Image

PowerShell for SQL Server Essentials

By : Donabel Santos
Book Image

PowerShell for SQL Server Essentials

By: Donabel Santos

Overview of this book

Table of Contents (15 chapters)
PowerShell for SQL Server Essentials
Credits
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Preface
Implementing Reusability with Functions and Modules
Index

Managing logins, users, and permissions


PowerShell and SMO can help pull a list of SQL Server logins, database users, and permissions. Since a login is an instance-level object, you can use the SMO Server object to pull information about every login registered in your instance. You can also list all the server roles this login belongs to, as shown in the following snippet:

Import-Module SQLPS -DisableNameChecking

#current server name
$servername = "ROGUE"

$server = New-Object "Microsoft.SqlServer.Management.Smo.Server" $servername

$result = @()

$server.Logins |
Where-Object IsSystemObject -EQ $false |
ForEach-Object {
   $login = $_
   $object = [pscustomobject] @{
      Login = $login.Name
      LoginType = $login.LoginType
      CreateDate = $login.CreateDate
      ServerRoles = $login.ListMembers()
   }
   $result += $object
}
$result |
Format-Table -AutoSize

A sample output is provided in the following screenshot:

Each SMO login object also has access to additional methods such as...