Skip to content
Advertisement

How to parameterize logins when executing SQL from PowerShell command

How do we run CREATE LOGIN ... against a variable string?

enter image description here

I’m executing the following command:

Invoke-Sqlcmd -ServerInstance $ServerInstance -Database 'master' -Username $DBAdminAccount -Password $DBAdminPassword -Variable $SqlVariables -InputFile $ArtifactStagingDirectoryMasterDBSetup.sql

MasterDBSetup.sql:

....
    IF NOT EXISTS (SELECT name  FROM sys.sql_logins WHERE name = '$(SvcRRRComparisonUser)')
    BEGIN 
        CREATE LOGIN '$(SvcRRRComparisonUser)' WITH PASSWORD = '$(RRRComparisonUserPassword)'
    END
....

How do we run CREATE LOGIN ... against $(SvcRRRComparisonUser) ?

Advertisement

Answer

In the $SqlVariables:

$SqlVariables = @("SvcRRRComparisonUser='user1',RRRComparisonUserPassword='pass1'")

Then in the SQL file:

IF NOT EXISTS (SELECT name  FROM sys.sql_logins WHERE name = $(SvcRRRComparisonUser)
BEGIN 
    CREATE LOGIN $(SvcRRRComparisonUser) WITH PASSWORD = $(RRRComparisonUserPassword)
END
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement