2

I cant seem to get a PS variable called $sqlParameters to be used in an SQL script, any clues to what I am doing wrong?

PowerShell:

$sqlParameters = "powerShellVar = 'CONTOSO\cmpsvc'"
invoke-sqlcmdInvoke SQL script using Powershell variables -inputfile "c:\temp\test.sql" -serverinstance SRVSCCM\MSSQLSERVER -variable $sqlParameters 

SQL:

CREATE LOGIN [$sqlParameters] FROM WINDOWS; 
USE test
EXEC sp_addrolemember N'db_owner', N'$sqlParameters'
GO

James

2 Answers 2

1

YOu can try something like this:

$MyArray = "MyVar1 = 'String1'", "MyVar2 = 'String2'"  
Invoke-Sqlcmd -Query "SELECT `$(MyVar1) AS Var1, `$(MyVar2) AS Var2;" -Variable $MyArray

or something like this:

$query=@'
CREATE LOGIN [$sqlParameters] FROM WINDOWS; 
USE test
EXEC sp_addrolemember N'db_owner', N'$sqlParameters'
GO
'@

Invoke-Sqlcmd -Query $query 

But if you have a file, then you have to use T-sql variables only cause SQL will understand in that way only:

Invoke-Sqlcmd -InputFile "C:\Folder\SQLCmd.sql"

Hope it helps.

Sign up to request clarification or add additional context in comments.

4 Comments

Hey, actually it doe not like the variable?
Invoke-Sqlcmd : User or role '$name' does not exist in this database. At line:10 char:1 + Invoke-Sqlcmd -Query $query
$name= 'CONTOSO\cmpsvc' $query=@' USE test EXEC sp_addrolemember N'db_owner', N'$name' GO '@ Invoke-Sqlcmd -Query $query
@JamesAtance: Accept the answer if it helps you . That would be appreciable.
0

One way you could do it is to use Get-Contents and then get Powershell to do the variable expansion, something like this:

$sqlParameters = 'CONTOSO\cmpsvc'"
Invoke-SqlCmd -Query ($ExecutionContext.InvokeCommand.ExpandString(Get-Contents 'my_file.sql'))

Or an easier way would be to use the format string. Change your file contents to this:

CREATE LOGIN [{0}] FROM WINDOWS; 
USE test
EXEC sp_addrolemember N'db_owner', N'$sqlParameters'
GO

Then your Powershell code would be come this:

$sqlParameters = 'CONTOSO\cmpsvc'"
Invoke-SqlCmd -Query ((Get-Contents 'my_file.sql') -f $sqlParameters)

1 Comment

Strange as I cant get any of these to work, Does any one have another idea. All I want to do is add permissions to DB's based on a Powershell variable?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.