Create a Secondary SA (Admin) Account for MSSQL

Create a Secondary SA (Admin) Account for MSSQL

In the event that you have lost or forgotten your SQL administrator password, the following script can create an additional administrator SA user account that you can use to log in.  This is preferable over resetting the SA password because changing the password would break any applications that had the old password stored.

 

  1. $InstanceName = 'MSSQLServer'
  2. $NewUser = 'sa2'
  3. $NewPassword = '12AeAOuaOE,.'

  4. #--------------------

  5. $Instance_List_Path = "HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL\"


  6. if(!$InstanceName){
  7. $Instances = (Get-Item $Instance_List_Path).Property
  8. if($Instances.Count -gt 1){
  9. Write-Host "No instance name specified. Valid values are:"
  10. Write-Host $Instances
  11. } elseif ($Instances.Count -eq 1) {
  12. $InstanceName = $Instances;
  13. Write-Information "SQL Instance not specified. Using $($InstanceName)"
  14. } else {
  15. Write-Host "Unable to detect SQL instances."
  16. }
  17. }

  18. if($InstanceName){

  19. $ServiceDisplayName = "SQL Server ($($InstanceName))"
  20. $ServiceName = Get-Service -DisplayName $ServiceDisplayName


  21. $InstanceLocation = Get-ItemPropertyValue $Instance_List_Path -Name $InstanceName

  22. $InstanceParameters = "HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server\$($InstanceLocation)\MSSQLServer\Parameters"
  23. $ArgName = "SQLArg99"

  24. Set-ItemProperty -Path $InstanceParameters -Name $ArgName -Value "-m"

  25. Stop-Service $ServiceName -Force
  26. Start-Service $ServiceName

  27. Start-Sleep -Seconds 1

  28. if($InstanceName -ieq 'MSSQLServer'){
  29. $ServerInstance = "(local)"
  30. } else {
  31. $ServerInstance = "(local)\$($InstanceName)"
  32. }

  33. $Query = "
  34. --Enable Administrator Access
  35. CREATE LOGIN [BUILTIN\Administrators] FROM WINDOWS
  36. GO

  37. ALTER SERVER ROLE sysadmin ADD MEMBER [BUILTIN\Administrators]
  38. GO

  39. --Enable Regular User Access
  40. --CREATE LOGIN [BUILTIN\Users] FROM WINDOWS
  41. --GO

  42. ALTER SERVER ROLE sysadmin ADD MEMBER [BUILTIN\Users]
  43. GO

  44. --Create a secondary admin user
  45. CREATE LOGIN [$($NewUser)] WITH PASSWORD=N'$($NewPassword)', CHECK_EXPIRATION=OFF, CHECK_POLICY=OFF
  46. GO

  47. ALTER SERVER ROLE [sysadmin] ADD MEMBER [$($NewUser)]
  48. GO
  49. "
  50. Invoke-Sqlcmd -ServerInstance $ServerInstance -Query $Query

  51. Remove-ItemProperty -Path $InstanceParameters -Name $ArgName
  52. Stop-Service $ServiceName -Force
  53. Start-Service $ServiceName

  54. }