Skip to content

Instantly share code, notes, and snippets.

@fagnercarvalho
Last active February 25, 2021 01:44
Show Gist options
  • Save fagnercarvalho/30e898371037cac86db500c577ad43e5 to your computer and use it in GitHub Desktop.
Save fagnercarvalho/30e898371037cac86db500c577ad43e5 to your computer and use it in GitHub Desktop.
Get blob from SQL Server database
## Export of "larger" Sql Server Blob to file
$Server = ".";
$Database = "DatabaseName";
$Dest = "C:\Export\";
$bufferSize = 8192;
$Sql = "select TOP 1 'Image.png', COLUMN from TABLE";
$con = New-Object Data.SqlClient.SqlConnection;
$con.ConnectionString = "Data Source=$Server;" +
"user id=user;Password=password;" +
"Initial Catalog=$Database";
$con.Open();
$cmd = New-Object Data.SqlClient.SqlCommand $Sql, $con;
$rd = $cmd.ExecuteReader();
$out = [array]::CreateInstance('Byte', $bufferSize)
# Looping through records
While ($rd.Read())
{
Write-Output ("Exporting: {0}" -f $rd.GetString(0));
$fs = New-Object System.IO.FileStream ($Dest + $rd.GetString(0)), Create, Write;
$bw = New-Object System.IO.BinaryWriter $fs;
$start = 0;
# Read first byte stream
$received = $rd.GetBytes(1, $start, $out, 0, $bufferSize - 1);
While ($received -gt 0)
{
$bw.Write($out, 0, $received);
$bw.Flush();
$start += $received;
$received = $rd.GetBytes(1, $start, $out, 0, $bufferSize - 1);
}
$bw.Close();
$fs.Close();
}
$fs.Dispose();
$rd.Close();
$cmd.Dispose();
$con.Close();
Write-Output ("Finished");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment