title: Pass a powershell variable into a SQL value during out-datatable (invoke-sqlcmd2)
body: <p>I want to insert a PowerShell variable value with a Select as I build a datatable from a SQL query. </p>
  
  <p>Borrowed function invoke-sqlcmd2 from TechNet gallery and dot-sourced it in. </p>
  
  <pre><code>$NewSequenceID = invoke-sqlcmd2 -ServerInstance "MyServer" -Database "MyDB" -Query "INSERT INTO [Sequence] (TimeStarted) SELECT GETDATE(); SELECT max(SequenceID) as SequenceID FROM [Sequence]" | foreach { $_.SequenceID }
  </code></pre>
  
  <p>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. </p>
  
  <p>Then I have this: </p>
  
  <pre><code>$PollTime = Get-Date -format "yyyy-MM-dd HH:mm:ss"
  </code></pre>
  
  <p>Then I want to do this: (Edit: This statement is not working - error message at the bottom)</p>
  
  <pre><code>$AuditUserOutput = invoke-sqlcmd2 -ServerInstance "MyServer2" -Database "MyDB2" -Query "SELECT $NewSequenceID, $PollTime, [USERID], [PID], [UDATE] FROM [MyTable]"  -As 'Datatable'
  </code></pre>
  
  <p>And do some things with the table, then write it after with write-datatable. </p>
  
  <p>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. </p>
  
  <p>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? </p>
  
  <p>PS Error is: Exception calling "Fill" with "1" argument(s): "Invalid pseudocolumn "$NewSequenceID"."</p>