Variable substitution in a powershell script

Hi,
I’m using here-string inside a powershell script to create a multi-line sql script to be executed shortly after I create a database.
The relevant section is as follows and values have been altered:

[string] $SqlUserName = ‘MYUSERNAME’
[string] $DatabaseName = $OctopusParameters[‘targetDatabaseName’]

$ownershipchange = @"

use [$($DatabaseName)];

ALTER AUTHORIZATION ON DATABASE::$($DatabaseName) TO [sa];

IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE [name] = N’$($SqlUserName)’)
BEGIN
CREATE USER [$($SqlUserName)] FROM LOGIN [$($SqlUserName)];
END

IF NOT EXISTS (SELECT 1 FROM sys.database_role_members rm INNER JOIN sys.database_principals u ON rm.member_principal_id = u.principal_id
INNER JOIN sys.database_principals r ON r.principal_id = rm.role_principal_id WHERE u.[name] = N’$($SqlUserName)’ AND r.[name] = N’db_owner’)
BEGIN
ALTER ROLE [db_owner] ADD MEMBER [$($SqlUserName)];
END

"@

Write-Host $ownershipchange

What ends up appearing on the deployment log is the following:

use [MyDatabaseDEV];

ALTER AUTHORIZATION ON DATABASE::MyDatabaseDEV TO [sa];

IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE [name] = N’’)
BEGIN

CREATE USER [] FROM LOGIN [];

END

IF NOT EXISTS (SELECT 1 FROM sys.database_role_members rm INNER JOIN sys.database_principals u ON rm.member_principal_id = u.principal_id INNER JOIN sys.database_principals r ON r.principal_id = rm.role_principal_id WHERE u.[name] = N’’ AND r.[name] = N’db_owner’)
BEGIN

ALTER ROLE [db_owner] ADD MEMBER [];

END

Essentially, the values I wanted to substitute turned into a empty string whenever they’re enclosed by single quotes or braces. Am I not properly escaping some characters? Thanks.

Hi Tristan,

Thanks for getting in touch! The syntax looks fine, we tested it on our end without any issues. We are wondering now how/where the script is being executed? Is it inside a script step, a script file in a package?

Would you please be able to attach a full deployment log where you are trying to run this script?
https://octopus.com/docs/how-to/get-the-raw-output-from-a-task

Looking forward to hearing from you. :slight_smile:

Best regards,
Daniel

Hi Daniel,
This snippet I had mentioned is part of a function and that function (along with others) is defined inside a script step, I call that function at the end of the script step. It turns out that I had not passed the $SqlUserName parameter after having a colleague look over my script step and that’s why it was not expanding the variable correctly. Thanks!