title: Where must variables in PowerShell here-strings be initialized?
body: <p>I have a rather complex SQL query I want to use in a here-string in a PowerShell script. Inside the query, I want to replace certain values with PowerShell variables. I'm trying to understand exactly where I need to declare and initialize the variables that will be used in the here-string.</p>
  
  <p>Simplified example:</p>
  
  <pre><code>$SqlQuery = @"
  update MyTable 
  set foo = $bar
  where baz = $quux
  "@
  
  ...
  
  foreach ($part in $parts) {
      $bar = $part[0]
      $quux = $part[1]
  
      Run-SqlNonQuery $SqlQuery    #Run-SqlNonQuery is a funct. that executes the query
  }
  </code></pre>
  
  <p>I'm declaring the here-string at the top, and it references a couple of PowerShell variables, $bar and $quux, that change each time thru the loop. </p>
  
  <p>However, I'm getting errors when I run my script. When I run a SQL trace, there's no value where the PowerShell variables appear in the PS script.</p>
  
  <p>Do the PowerShell variables get interpolated when called in a here-string like this? Do I need to put the entire here-string <em>inside</em> the loop where the variables are initialized? What's the right structure for something like this?</p>
  
  <p>I'm running PowerShell on Windows 7, .Net 4, VS2010. I'm not clear on the version; <code>$Host</code> returns</p>
  
  <pre><code>Name             : PowerConsole
  Version          : 1.0.30222.0
  </code></pre>
  
  <p>but <code>$PSVersionTable</code> returns</p>
  
  <pre><code>PSVersion             2.0                                                      
  PSCompatibleVersions  {1.0, 2.0}
  BuildVersion          6.1.7601.17514
  </code></pre>