apyo
apyo

Reputation: 1

Pass a powershell variable into a SQL value during out-datatable (invoke-sqlcmd2)

I want to insert a PowerShell variable value with a Select as I build a datatable from a SQL query.

Borrowed function invoke-sqlcmd2 from TechNet gallery and dot-sourced it in.

$NewSequenceID = invoke-sqlcmd2 -ServerInstance "MyServer" -Database "MyDB" -Query "INSERT INTO [Sequence] (TimeStarted) SELECT GETDATE(); SELECT max(SequenceID) as SequenceID FROM [Sequence]" | foreach { $_.SequenceID }

This generates a new sequence ID and stamps the time we started the batch. Results in a single number which will identify this run. Verified with 'write $NewSequenceID'. I want to keep later results from queries together with this SequenceID for analysis.

Then I have this:

$PollTime = Get-Date -format "yyyy-MM-dd HH:mm:ss"

Then I want to do this: (Edit: This statement is not working - error message at the bottom)

$AuditUserOutput = invoke-sqlcmd2 -ServerInstance "MyServer2" -Database "MyDB2" -Query "SELECT $NewSequenceID, $PollTime, [USERID], [PID], [UDATE] FROM [MyTable]"  -As 'Datatable'

And do some things with the table, then write it after with write-datatable.

If I select NULL for the first two values and grab the other three from the existing table, it works fine. I want to add the $NewSequenceID and $PollTime from the previous statements.

I've read a dozen pages about using ` (backtick), $, {}, and on and on, but I haven't gotten it right. Can someone help with the correct syntax for inserting these variable values into the selection?

PS Error is: Exception calling "Fill" with "1" argument(s): "Invalid pseudocolumn "$NewSequenceID"."

Upvotes: 0

Views: 11142

Answers (2)

apyo
apyo

Reputation: 1

I was able to work around this by first creating a variable to store the query text, which allowed for the natural substitution I needed:

$AuditUserQuery = "SELECT '$NewSequenceID', '$PollTime', [USERID], [PID], [UDATE] FROM [AUDITUSER]" 

Then calling that variable as the $query when building the datatable.

This avoided the parameterization problem experienced before.

Upvotes: 0

Adi Inbar
Adi Inbar

Reputation: 12321

You're interpolating the variables correctly in PowerShell. If I'm understanding this correctly, the problem is with your SQL query. I'm going to make an inference here, but I think this is probably what you want:

$AuditUserOutput = invoke-sqlcmd2 -ServerInstance "MyServer2" -Database "MyDB2" -Query "SELECT [NewSequenceID], [PollTime], [USERID], [PID], [UDATE] FROM [MyTable] WHERE NewSequenceID = '$NewSequenceID' AND PollTime = '$PollTime'"  -As 'Datatable'

If not, please clarify by responding to the questions above.

Upvotes: 1

Related Questions