我使用SQL Server,并且有一个名为[dbo].[TemplatePackageContent]
的SQL表,该表只有两个字段:
[TemplatePackageContentId] [uniqueidentifier] NOT NULL,
[Content] [varbinary](max) NULL
我想创建PowerShell脚本,该脚本从此表中读取全部内容,并且对于每行,它将基于{TemplatePackageContentId}.pkg
字段在给定目录中以格式Content
生成文件。
到目前为止,我已经设法读取表的全部内容:
param(
[string] $dataSource = "(localdb)\mssqlLocalDb",
[string] $database = "Hda_tenancy1",
[string] $sqlCommand = $("SELECT * FROM TemplatePackageContent")
)
$connectionString = "Data Source=$dataSource; " +
"Integrated Security=SSPI; " +
"Initial Catalog=$database"
$connection = new-object system.data.SqlClient.SQLConnection($connectionString)
$command = new-object system.data.sqlclient.sqlcommand($sqlCommand,$connection)
$connection.Open()
$adapter = New-Object System.Data.sqlclient.sqlDataAdapter $command
$dataset = New-Object System.Data.DataSet
$adapter.Fill($dataSet) | Out-Null
$connection.Close()
$dataSet.Tables
现在,我想对接收到的结果进行转换,大概是遍历每一行。
我发现this article解决了c#中的类似问题,并且我正在考虑从那里使用一些逻辑并将其转换为PowerShell脚本。
将所有“内容”字段转换为.pkg格式的文件的最佳方法是什么?我应该使用哪种库或哪种方法? 有任何想法吗? 干杯
答案 0 :(得分:0)
我最终得到了这个解决方案:
param(
[string] $dataSource = "(localdb)\mssqlLocalDb",
[string] $database = "Hda_tenancy1",
[string] $templatePath = "C:\dev\hubadvance\Seeding\Templates\"
)
$sqlCommand = $("SELECT * FROM TemplatePackageContent");
$connection = new-object System.Data.SqlClient.SQLConnection("Data Source=$dataSource;Integrated Security=SSPI;Initial Catalog=$database");
$cmd = new-object System.Data.SqlClient.SqlCommand($sqlCommand, $connection);
$connection.Open();
$reader = $cmd.ExecuteReader();
$results = @();
while ($reader.Read())
{
$row = @{}
for ($i = 0; $i -lt $reader.FieldCount; $i++)
{
$row[$reader.GetName($i)] = $reader.GetValue($i);
}
$results += new-object psobject -property $row;
}
$connection.Close();
foreach ($row in $results)
{
Write-Host $row.TemplatePackageContentId;
$path = $templatePath + $row.TemplatePackageContentId + ".pkg";
[System.IO.File]::AppendAllText($path, $row.Content);
}