title: Unicode support for Invoke-Sqlcmd in PowerShell
body: <p>The PowerShell <a href="http://msdn.microsoft.com/en-us/library/hh245198">sqlps module</a> provides core support for SQL Server access from within PowerShell and its <a href="http://msdn.microsoft.com/en-us/library/cc281720">Invoke-Sqlcmd</a> cmdlet is its main workhorse for executing literal queries or SQL script files (analogous to the non-PowerShell <a href="http://msdn.microsoft.com/en-us/library/ms162773.aspx">sqlcmd</a> utility). I recently tried some experiments to confirm that Invoke-Sqlcmd handles Unicode and had some surprising results.</p>
  
  <p>I started with this simple script file (named unicode.sql):</p>
  
  <pre><code>CREATE TABLE #customers
  
  ( [IdCust] int,
    [FirstName] nvarchar(25),
    [SurName] nvarchar(25)
  );
  INSERT INTO #customers VALUES (4, N'Hans', N'Grüßner')
  SELECT * FROM #customers;
  DROP TABLE #customers;
  </code></pre>
  
  <p>Note that the surname has some typical Unicode characters one might find in a German name, for example. </p>
  
  <hr>
  
  <h2>Results</h2>
  
  <p><strong>SQL Server Management Studio:</strong> Renders correctly when output to grid or to text, e.g.</p>
  
  <pre><code>IdCust      FirstName                 Surname
  ----------- ------------------------- -------------------------
  4           Hans                      Grüßner
  </code></pre>
  
  <p><strong>sqlcmd utility:</strong> Renders correctly whether run from a DOS shell or a PowerShell, e.g.</p>
  
  <pre><code>C:\&gt; sqlcmd -S .\SQLEXPRESS -i unicode.sql
  
  IdCust      FirstName                 Surname
  ----------- ------------------------- -------------------------
            4 Hans                      Grüßner
  </code></pre>
  
  <p><strong>PowerShell Invoke-Sqlcmd:</strong> Renders incorrectly (whether output as text as shown below or piped into Out-Gridview):</p>
  
  <pre><code>PS&gt; Invoke-Sqlcmd -Server .\sqlexpress -InputFile unicode.sql
  
  IdCust FirstName           Surname
  ------ ---------           -------
       4 Hans                Gr??ner
  </code></pre>
  
  <p>The <a href="http://msdn.microsoft.com/en-us/library/cc281720">MSDN documentation</a> for Invoke-Sqlcmd mentions Unicode only in passing, comparing its command-line switches with those of sqlcmd, showing that while the latter has a <code>-u</code> option for outputting Unicode (which was not even needed in my experiment above), Invoke-Sqlcmd has <em>no</em> equivalent parameter. </p>
  
  <p>I have found nothing at all regarding this point through extensive web searching but I still hold out hope that this is in some way a user error on my part. Is there a way to preserve the input data when retrieving it with Invoke-Sqlcmd in PowerShell?</p>