In the following powershell script I am attempting to call a Rest API, that returns a binary encoding of a file, and update a particular VARBINARY cell in my SQL server table with the content of the response.
$headers=@{}
$headers.Add("accept", "text/plain")
$headers.Add("authorization", "Bearer xyz")
$response = Invoke-WebRequest -Uri 'https://www.formstack.com/api/v2/download...' -Method GET -Headers $headers
$value = $response.Content
$sqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server=myServer; Database =myDB; User ID=uid; Password=pwd;"
$sqlConnection.Open()
$sqlCommand=$sqlConnection.CreateCommand()
$sqlCommand.CommandText = "UPDATE dbo.Table SET Document = $value WHERE Unique_ID ='123';"
$sqlCommand.ExecuteNonQuery()
I run into the following error:
Exception calling "ExecuteNonQuery" with "0" argument(s): "Incorrect syntax near '80'."
The "80" appears to be the second element of the byte array in $response.Content.
Is there a way to resolve this? This code otherwise works for inserting random values into the table, but I can't figure out how to insert the binary content.
UPDATE :
I got it to work by converting the byte array to a hexdecimal string with the following code:
$hexString = ($value | ForEach-Object ToString X2) -join ''
$valuehex = '0x' + $hexString