Search code examples
powershellinvoke-command

Simple SQL Insert with Powershell Invoke Command


Trying to run a logon script on a domain controlled computer through group policy. Works great on the Server with SQLserver module installed, but when converting code to use invoke-command and run from domain controlled computer, input into database is empty -- it changes from null to empty.

Code that works:

$var1 = $env:xxx
$var2 = $env:xxx
$var3 = $env:xxx

invoke-sqlcmd -Query "insert into tblxxx (abc, def, ghi) values('$var1', '$var2', '$var3')" -connectionstring <connectionstring>

Code that doesn't work:

$var1 = $env:xxx
$var2 = $env:xxx
$var3 = $env:xxx

invoke-command -computername <server> {invoke-sqlcmd -Query <same query as above> -connectionstring <connectionstring>}

What am I doing wrong?


Solution

  • Use $using:var1 inside the Invoke-Command because the variable $var1 is not known in the new scope.