How to script SQL database roles using powershell?

Bob 1971 1 Reputation point
2021-03-22T20:03:02.99+00:00

Hi everyone.

I am trying to script SQL database roles as the built in SSMS "Task", "Generate scripts" is able to do it. An example of the output can be found below.

I set the following Scripter options:

$scripter.Options.IncludeDatabaseRoleMemberships = $true
$scripter.Options.Permissions = $true

However I only get the CREATE USER... part. Does any one have an example of how to also get the ALTER ROLE statements?

Kind regards
Bob

USE [TestDB]
GO
CREATE USER [MyDBuser] FOR LOGIN [MyDBuser] WITH DEFAULT_SCHEMA=[dbo]
GO
ALTER ROLE [db_executor] ADD MEMBER [MyDBuser]
GO
ALTER ROLE [db_owner] ADD MEMBER [MyDBuser]
GO
ALTER ROLE [db_backupoperator] ADD MEMBER [MyDBuser]
GO
ALTER ROLE [db_datareader] ADD MEMBER [MyDBuser]
GO
ALTER ROLE [db_datawriter] ADD MEMBER [MyDBuser]
GO
SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
12,775 questions
Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,383 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Olaf Helper 40,916 Reputation points
    2021-03-23T07:40:10.917+00:00

    $scripter.Options.IncludeDatabaseRoleMemberships = $true

    That scripts only members of a database role, not the role itself. See DatabaseRole.Script Method

    And for the complete SMO documentation see Overview (SMO)

    0 comments No comments