This function allows administrators to regain access to local or remote SQL Servers by either resetting the sa password, adding sysadmin role to existing login, or adding a new login (SQL or Windows) and granting it sysadmin privileges.
This is accomplished by stopping the SQL services or SQL Clustered Resource Group, then restarting SQL via the command-line using the /mReset-SqlAdmin paramter which starts the server in Single-User mode, and only allows this script to connect.
Using Reset-SqlAdmin will restart your SQL Server. I chose this method because it is the most effective, cross-version method. Impersonating tokens may not work in all situations.
Once the service is restarted, the following tasks are performed:
- Login is added if it doesn’t exist
- If login is a Windows User, an attempt is made to ensure it exists
- If login is a SQL Login, password policy will be set to OFF when creating the login, and SQL Server authentication will be set to Mixed Mode.
- Login will be enabled and unlocked
- Login will be added to sysadmin role
If failures occur at any point, a best attempt is made to restart the SQL Server.
In order to make this script as portable as possible, the original module on Script Center only uses System.Data.SqlClient and Get-WmiObject are used (as opposed to requiring the Failover Cluster Admin tools or SMO). If using this function against a remote SQL Server, ensure WinRM is configured and accessible. If this is not possible, run the script locally.
Tested on Windows XP, 7, 8.1, Server 2012 and Windows Server Technical Preview 2. Tested on SQL Server 2005 SP4 through 2016 CTP2.
Reset-SqlAdmin -SqlServer sqlcluster
Prompts for password, then resets the "sa" account password on sqlcluster.
Reset-SqlAdmin -SqlServer sqlserver\sqlexpress -Login ad\administrator
Adds the domain account "ad\administrator" as a sysadmin to the SQL instance.
If the account already exists, it will be added to the sysadmin role.
Reset-SqlAdmin -SqlServer sqlserver\sqlexpress -Login sqladmin
Prompts for passsword, then adds a SQL Login "sqladmin" with sysadmin privleges.
If the account already exists, it will be added to the sysadmin role and the password will be reset.