Search code examples
powershellinvoke-sqlcmd

Invoke-Sqlcmd : Incorrect syntax near '¦'. Encoding issue


In a PowerShell script, I read a config file and run some SQL queries. This works fine if I copy the code and paste it into PowerShell ISE.

But if I run the script by right clicking the file > Run with Powershell, I get an error

Invoke-Sqlcmd : Incorrect syntax near '¦'

I only get this error if the query contains scandinavian characters 'æøå'.

$config = Get-Content -Path <path to file>\config.json | ConvertFrom-Json

$server = $config.server
$database = $config.database

Invoke-Sqlcmd -ServerInstance $server -Database $database -QueryTimeout 0 -Query "select Næringskode from Virksomhet"

config.json

{
    "server": "localhost",
    "database": "MyDatabase"
}

Solution

  • Make sure the script is saved in an encoding powershell 5.1 can recognize (I'm looking at Notepad in Win10 20h2) (ansi is probably the worst choice):

    ansi
    utf-16 le
    utf-16 be
    utf-8 with bom
    

    not (unless you're in powershell 7).

    utf-8
    

    Notepad can recognize utf-8.

    test.ps1:

    'æøå'