Created
August 17, 2017 04:29
-
-
Save rwilkes/7eab2be5af2e7a5a59eacd8172487d23 to your computer and use it in GitHub Desktop.
Simple POSH script to connect to SQL server and stream some table BLOBS a buffer to be reconstituted as proper files!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Function Select-TableBlob { | |
param( | |
[string]$connectionString="Initial Catalog=Anaqua;Data Source=HFX.anaqua.local;Trusted_Connection=True;", | |
[string]$sqlQuery="SELECT OriginalFile, ThumbNailBlob, ThumbNailBlob FROM FileInformation WHERE ((ThumbNailBlob IS NOT NULL) and (substring(convert(varchar(max),convert(varbinary(max),ThumbNailBlob)), 0, 3) like 'BM'))", | |
[string]$tableName, | |
[string]$blobColumn, | |
[string]$destination=(Get-Location | Split-Path), | |
[int]$blobLimit=10 | |
) | |
[System.Data.SqlClient.SQLConnection]$connection = New-Object System.Data.SqlClient.SQLConnection | |
$connection.ConnectionString=$connectionString | |
if(!$sqlQuery) { | |
if($tableName -and $blobColumn) { | |
$sqlQuery="SELECT " | |
$sqlQuery+=$blobColumn | |
$sqlQuery+=" FROM " | |
$sqlQuery+=$tableName | |
$sqlQuery+=" WHERE " | |
$sqlQuery+=$blobColumn | |
$sqlQuery+=" IS NOT NULL" | |
} | |
} | |
[System.Data.SqlClient.SqlCommand]$command= New-Object System.Data.SqlClient.SqlCommand($sqlQuery,$connection) | |
$command.CommandTimeout=120 | |
$connection.Open() | |
[System.Data.SqlClient.SqlDataReader]$reader = $command.ExecuteReader([System.Data.CommandBehavior]::SequentialAccess) | |
while ($reader.Read()) | |
{ | |
[string]$originalFileName=$reader.GetValue(0) | |
[string]$newFileName=[System.IO.Path]::GetFileNameWithoutExtension($originalFileName) | |
$newFileName+="_ThumbNailBlob" | |
$newFileName+=[System.IO.Path]::GetExtension($originalFileName) | |
$filepath = Join-Path -Path $destination -ChildPath $newFileName | |
[System.Data.SqlTypes.SqlBytes]$sqlBytes = $reader.GetSqlBytes(1) | |
[byte[]]$buffer = New-Object byte[] -ArgumentList $reader.GetBytes(2,0,$null,0,$sqlBytes.Length) | |
#[byte[]]$buffer = $null | |
$reader.GetBytes(2,0,$buffer,0,$buffer.Length) | |
[System.IO.FileStream]$fs = New-Object System.IO.FileStream($filePath,[System.IO.FileMode]::Create,[System.IO.FileAccess]::Write) | |
$fs.Write($buffer, 0, $buffer.Length) | |
$fs.Close() | |
#Write-Output "Wrote " $newFileName " to " $destination | |
} | |
} | |
Select-TableBlob |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment