使用PowerShell导出SQL DB

时间:2014-09-05 17:21:36

标签: sql powershell export jpeg

我正在尝试导出存储在远程SQL服务器中的图像的BLOB数据,并将它们保存到本地计算机上的.jpg导出文件夹中。在解决第一个错误或帮助我修改工作连接以获取blob数据并将其转换为本地计算机上的.jpgs方面的任何帮助都将非常感激。

我找到了以下代码

    $Server = "?????"     
$Database = "??????"   
$Dest = "c:\Export\"             
$bufferSize = 8192               

$sqlCommand = " SELECT ID?????1              
         FROM dbo.W?????e; "            

$authentication = "Integrated Security=SSPI;"          
$connectionString = "Provider=sqloledb; " +
                    "Data Source=$dataSource; " +
                    "Initial Catalog=$database; " +
                    "$authentication; "


$connection = New-Object System.Data.OleDb.OleDbConnection $connectionString
$command = New-Object System.Data.OleDb.OleDbCommand $sqlCommand,$connection
$connection.Open() 

$reader = $command.ExecuteReader()            
$out = [array]::CreateInstance('Byte', $bufferSize)            

While ($reader.Read())            
{            
    $fileStream = New-Object System.IO.FileStream ($Dest + $reader.GetString(0)), Create, Write            
    $binaryWriter = New-Object System.IO.BinaryWriter $fileStream            

    $start = 0            
    $received = $reader.GetBytes(1, $start, $out, 0, $bufferSize - 1)            
    While ($received -gt 0)            
    {            
       $binaryWriter.Write($out, 0, $received)            
       $binaryWriter.Flush()            
       $start += $received            
       $received = $reader.GetBytes(1, $start, $out, 0, $bufferSize - 1)            
    }            

    $binaryWriter.Close()            
    $fileStream.Close()            
}            

$fileStream.Dispose()           
$reader.Close()            
$command.Dispose()            
$connection.Close()      

运行代码时遇到错误。 error

我可以使用此代码连接到数据库,但我不理解streamprocess足以将代码网格划分以实现我想要的目标

$Server = "?????";         # SQL Server Instance.            
$Database = "?????";            
$Dest = "c:\Export\";             # Path to export to.            
$bufferSize = 8192;               # Stream buffer size in bytes.         
    $connString = "data source=?????,1433;Initial catalog=?????;Integrated Security=TRUE;"
$QueryText = "SELECT ID?????1              
        FROM dbo.W??????e;"


$SqlConnection = new-object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = $connString
$SqlCommand = $SqlConnection.CreateCommand()
$SqlCommand.CommandText = $QueryText

$DataAdapter = new-object System.Data.SqlClient.SqlDataAdapter $SqlCommand
$dataset = new-object System.Data.Dataset
$DataAdapter.Fill($dataset)

$dataset.Tables[0] 

Write-Output ("Finished");

这是我想要完成的,但是我收到错误,将字节转换为字符串 HERE

2 个答案:

答案 0 :(得分:1)

我敢打赌你的命令超时太短了。默认情况下,it is 30 seconds。 Blob通常非常大,如果花费超过30秒从数据库中读取它们,我不会感到惊讶。尝试将超时设置为真正非常大的东西:

$command.CommandTimeout = [Int32]::MaxValue

答案 1 :(得分:0)

我得到了同样的错误。

将原始代码更接近SQL Server名称用于实例。如果您在本地服务器上执行此操作,则可以使用"。"作为服务器名称。

  

$ Server ="。&#34 ;;