[HOWTO] Convert Image File to SQL data type varbinary using PowerShell

In one of the projects I’m currently working on, I needed to insert a PNG file into a database column of type varbinary.

I failed with my first attempts, but thanks to some blog posts and some threads on StackOverflow, I was able to come up with the following solution by assembling some of the information I found on the Internet.

# to create a hex-string from a PNG file execute the following commands in PowerShell

# replace C:\PATH\TO\FILE.png with the path to the file you want to convert
[Byte[]]$bytes = Get-Content -Encoding Byte C:\PATH\TO\FILE.png
$hexString = ($bytes | ForEach-Object ToString X2) -join ''
$valueToBeInserted = '0x' + $hexString
$valueToBeInserted | clip

After the execution of the above commands, the value to be inserted into the database column of type varbinary is on the clipboard. To add the value to the database column either directly insert it using Microsoft SQL Server Management Studio or by executing the following insert into statement:


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Website Powered by WordPress.com.

Up ↑

%d bloggers like this: