Error when inserting strings with $( with Invoke-SqlCmd in Powershell

Question:

Setup:

Test:

Following work:

Following fails with the error below:

Test:

Following work:

Following fails with the error below:

(5′)”

Error:
Invoke-Sqlcmd :
At line:1 char:1
+ Invoke-Sqlcmd -Database “databasename” -ServerInstance “hostname” -Ou …
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ParserError: (:) [Invoke-Sqlcmd], ParserException
+ FullyQualifiedErrorId : ExecutionFailureException,Microsoft.SqlServer.Management.PowerShell.GetScriptCommand

Aftersome research I found that $( provides functionality in powershell thus is reserved. However I tried escaping the parenthesis but with no success. I’ve tried finding alternatative. Any ideas on how I can do this? If I use the CHAR function in SQL Server that works but it would be a pain to deal with in my code. Thank you.

Answer:

The issue seems that the $( is a reserved word in Powershell thus to make this work I had use the CHAR function to store the $ (CHAR(36)). Once I did this it worked but for this project I abandoned using the Invoke-SqlCmd command and used a standard ADO.NET method. It seems that the Invoke-SqlCmd wants to parse the command and for the reserved combination continues to see the reserved word even if you escape the characters.

Source:

Error when inserting strings with $( with Invoke-SqlCmd in Powershell by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply