Tuesday, 10 September 2019

Powershell to create SQL Server login

This script was designed to be executed in an Azure Devops pipeline, although it could be easily adapted for other automated processes

 [CmdletBinding()]  
 param (  
   [Parameter(Mandatory=$True)] [string] $DBPassword,  
    [string]$sqluser,  
     [string]$sqlpass  
 )  
   
 ################################################################################################  
 #  
 # sets up logins on the SQL server  
 # "MyLogin" could be passed in as a parameter in a future version  
 #  
 ################################################################################################  
   
 Import-Module sqlserver  
 $ServerName = hostname  
   
 $server = hostname  
   
 # Change Authentication to mixed  
 $smo = new-object ('Microsoft.SqlServer.Management.Smo.Server') "$server"  
 if(!($smo.Settings.LoginMode -eq "Mixed")){  
   $smo.Settings.LoginMode = [Microsoft.SqlServer.Management.SMO.ServerLoginMode]::Mixed  
   $smo.Alter()  
   Restart-Service -Force MSSQLSERVER  
 }  
   
 $sqlCreateUsers=@"  
 if not exists (select loginname from master.dbo.syslogins where name = 'MyLogin')  
    CREATE LOGIN MyLogin WITH password = '$DBPassword', CHECK_POLICY = OFF  
 else  
    ALTER LOGIN [MyLogin] WITH PASSWORD=N'$DBPassword'  
 "@  
   
 # if credentials are available then use them, otherwise assume Windows auth  
 if ($sqluser -and $sqlpass) {  
   Invoke-Sqlcmd -ServerInstance $ServerName -Query $sqlCreateUsers -Username $sqluser -Password $sqlpass  
 } else {  
   Invoke-Sqlcmd -ServerInstance $ServerName -Query $sqlCreateUsers  
 }  
   


No comments:

Post a Comment