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 master key


In this recipe, we will create a database master key.

Getting ready

In this recipe, we will create a database master key for the master database. You can substitute a different database for this exercise if you wish.

The T-SQL equivalent of what we are trying to accomplish is as follows:

USE master
GO
CREATE MASTER KEY
ENCRYPTION BY PASSWORD = 'P@ssword'

How to do it...

Let's take a look at the steps required to complete the task:

  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 it:

    $VerbosePreference = "Continue"
    $masterdb =  $server.Databases["master"]
    
    if($masterdb.MasterKey -eq $null)
    {
       $masterkey = New-Object Microsoft.SqlServer.Management...