0

I have the following code:

$ItemsToItemGroups | Where-Object { $_.ItemGroupId -ne $null } | ForEach-Object {
    $Query = "INSERT INTO dbo.Items (ArticleNumber, ArticleNameDE, ArticleNameFR, ItemGroupId) VALUES ('{0}','{1}','{2}','{3}')" -f $_.ArticleNumber, $_.ArticleNameDE, $_.ArticleNameFR, $_.ItemGroupId
    Invoke-SqlCmd -ConnectionString $NewDBConnectionString -Query $Query
}

My problem is, that the string that gets inserted into the ArticleNameFR column sometimes is a string like this à l'anglaise - that breaks the insert statement, because of the single quote.

Is there an easy way how I can escape it in my statement so it doesn't break the operation?

I insert around 3000 rows and 95% work perfectly, but some throw an error because of the above.

I could simply replace the ' character in the string before I read it into the DB but I'd rather not do that because the data wouldn't be 100% correct then.

3
  • 1
    Single quotes are escaped by doubling them - or more correctly using parameters. Commented Oct 20, 2020 at 20:25
  • 1
    @DaleK thanks, that was easy, i just did $_.ArticleNameFR -replace "'","''" Commented Oct 20, 2020 at 20:30
  • Indeed, @SimonS - please see stackoverflow.com/a/64454230/45375 Commented Oct 20, 2020 at 22:36

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.