Search code examples
mysqlstringpowershellnewlinequotes

Powershell String keep CR & LF


I want to Insert a Blob in a MySQL Database via "MySql.Data.MySqlClient.MySqlConnection", it works fine but Powershell removes the Newline Characters from my Variable:

$configString = Get-Content config.xml 
$configString > test5.xml
$strAddConfig = "INSERT INTO config_xml(Version,ConfigXML,MD5,Comment,ClientMinVersion) VALUES('2','" + $($configString) + "','$configMD5','BLABLA','5.0.0.0')"

When I pipe the $configString variable into a Textfile, the CR&LF characters will keep, also when I input the blob via copy paste the Newline characters wil considered. I tried the "strAddConfig" line with different Quote combinations, but I wasn`t successful.

Thanks for help


Solution

  • # Read the text content *as a single, multi-line string*, using -Raw
    $configString = Get-Content -Raw config.xml
    
    # Use an expandable here-string for better formatting.
    $strAddConfig = @"
    INSERT INTO config_xml(Version,ConfigXML,MD5,Comment,ClientMinVersion)
    VALUES('2','$configString','$configMD5','BLABLA','5.0.0.0')
    "@
    

    Your (primary) problem was the use of Get-Content config.xml without -Raw, which stored an array of lines in $configString, and when an array is used in an expandable string ("...", with string interpolation), its (stringified) elements are space-separated:

    PS> $array = 'one', 'two'; "$array"
    one two