Database mirroring has been around since SQL Server 2005, and it’s turned out to be an excellent step up from log shipping. However, like log shipping, it is still only a database-level disaster recovery solution. Meaning that any logins, server role memberships or server-level permissions will not be mirrored over to the mirror server. This is where the DBA needs to plan ahead and create their own custom jobs to script and/or document these types of shortcomings.

My solution is to use Powershell. In this example, I have setup database mirroring for the AdventureWorks2012 database. For this demo, both instances, TEST1 and TEST2, are on the same physical server.

There are two logins on the principal server that currently do not exist on the mirror server. One is a SQL login, AWLogin1, and the other is a Windows Authenticated login, TRON2AWLogin2.

The first step of our Powershell script will need to connect to the principal server to generate a CREATE LOGIN script for those two logins. To generate the script, we need to grab the login name, the SID, and the hashed password if it’s a SQL login. This is accomplished by running the following code.

In this example, you can see we have one row for each of the two logins.

The next step of the Powershell script will need to write those two rows of data to a file on the mirror server. This is done using the System.IO.StreamWriterclass.

foreach($rowin$commandList.Tables[0].Rows)

{

try

{

$output=$row[“LoginScript”].ToString()

$stream.WriteLine($output)

}

catch

{

$stream.Close()

CheckForErrors

}

}

When there is a need to failover to the mirror server, the DBA can then open this script and run it. All logins will be created and with their original SID value and password.

The second half of the Powershell script will use the same procedures to script out any server role memberships or server-level permissions these two logins may have on the principal server. This is done using the following block of code.

From the output, you can see the TRONAWLogin2 is a member of the BULKADMIN server role and has the VIEW SERVER STATE permission. These two rows will be written to a file in the same file share as the previous file.

As before, once the database is failed over to the mirror server, the DBA can run this script to apply any missing permissions.

Finally, this Powershell script can be scheduled to run from any server; however, I choose to setup this job on the principal server. I schedule it to run once a day through SQL Agent. Each run of the script will overwrite the existing file, so if there are any logins or permissions that have been added or removed, it will show up in the latest version of the files.

Using this Powershell script can make it very easy to script out logins and permissions. While this example was used with database mirroring, then same strategy will work for log shipping. The entire Powershell script is below.