I am running into a character conversion problem when trying to export xml data from a SQL server table using Powershell 4.0. I'm using invoke-sqlcmd to run my sql server query, and found that many characters are not being interpreted correctly. For example, a >
character is being received as >
, and a <
character is being received as <
. Fractions, the degree symbol, formatted quotes, etc, are all doing the same thing. I wrote up several $string.replace commands below, which seems to fix about 80% of the problems, but when I spot check the results, I keep finding new characters that converted incorrectly.
Here is a sample of my SQL query and my replace statements:
$sql = [my sql select statement]
$result=Invoke-sqlcmd -Server $server -MaxCharLength 9000000 -Database $db -Username [myusername] -Password [mypassword] -Query $sql
$string=$result[0] | out-string
$string=$string.replace('<', '<')
$string=$string.replace('>', '>')
$string=$string.replace('&quot;', '"')
$string=$string.replace('amp;', '')
$string=$string.replace('“', '“')
$string=$string.replace('â€', '”')
$string=$string.replace('’', "’")
$string=$string.replace('–', "–")
$string=$string.replace('& ', "& ")
$string=$string.replace('½', "½")
$string=$string.replace('¼', "¼")
$string=$string.replace('�', "-")
So, I have two thoughts, and appreciate any feedback you may have:
1) I could keep exporting the data, spot checking, and writing a new replace statement (like above) when I find a problem. This seems to be time consuming and error prone. If I go this route, I'd hope to not reinvent the wheel. Has anyone found or created a list of commonly misinterpreted characters that I could start with?
2) The other option is to try to get to the root of the character conversion problem with my invoke-sqlcmd command so I don't have to do all of the replacements in the string. I have done a fair amount of research on this, but have not found anything to work properly. Does anyone have any thoughts for what I could change in my invoke-sqlcmd command to encode the data correctly?
I greatly appreciate any help that could be offered.
Thank you! Chris