I need to execute several “sqlcmd” command prompt in my PowerShell script. When I execute this command directly in powershell using ‘&’ operator - all works fine:
& sqlcmd -S SQLSRV -v DatabaseName=“MyDb” -i “.\MyScript.sql” -b
but, if I arrange ‘sqlcmd…’ to PowerShell variable - I have got error:
$sqlcommand = “sqlcmd -S SQLSRV -v DatabaseName=`"MyDb`” -i `".\MyScript.sql`" -b"
& : The term ‘sqlcmd -S SQLSRV -v DatabaseName=“MyDb” -i “.\MyScript.sql” -b’ is not recognized as the name of a cmdlet, function, script file, or operable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
How can I execute this “sqlcmd” command through variable ? Or may be make sense to use “Invoke-Expression” instead of “&” ?
Invoke-Expression $sqlcommand works properly.