#PSTip Add a SQL login to database roles using SMO

Note: This tip requires PowerShell 2.0 or above.

We can use SQL Server SMO object to add a SQL login to the database roles. For example, roles such as dbcreator, sysadmin, etc.

Let us see how we can do it using PowerShell and SMO.

Add-Type -AssemblyName "Microsoft.SqlServer.Smo, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"
$smo = New-Object Microsoft.SqlServer.Management.Smo.Server $env:ComputerName
$smo.Logins["Domain\SQLUser"].AddToRoles('sysadmin')
Share on: