从表中提取数据并使用PowerShell写入文件

时间:2017-05-17 20:26:58

标签: powershell scripting powershell-v2.0

我有一个SQL Server数据库,我需要从中提取数据并将其写入| - 分隔的.dat文件。

数据库名称:AppleDB

表:ApplePhoneAppleGear

ApplePhone的结构:

Id  Phone
1   6s
2   7s

AppleGear的结构:

Id  Gear
1   ear
2   watch

我需要一个脚本,从上面的两个表中提取信息并将其写入2个| - 分隔的.dat个文件。

ApplePhone.dat

Id|Phone
1|6s
2|7s

AppleGear.dat

Id|Gear
1|ear
2|watch

以下代码生成xls文件,但我需要使用|获取.dat文件分隔。

## ---------- Working with SQL Server ---------- ##

## - Get SQL Server Table data:
$SQLServer = 'myServer';
$Database = 'AppleDB';
$SqlQuery = @'
Select Id,Phone FROM [AppleDB].[dbo].[ApplePhone]
'@;

## - Connect to SQL Server using non-SMO class 'System.Data':
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection;
$SqlConnection.ConnectionString = `
"Server = $SQLServer; Database = $Database; Integrated Security = True";

$SqlCmd = New-Object System.Data.SqlClient.SqlCommand;
$SqlCmd.CommandText = $SqlQuery;
$SqlCmd.Connection = $SqlConnection;

## - Extract and build the SQL data object '$DataSetTable':
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter;
$SqlAdapter.SelectCommand = $SqlCmd;
$DataSet = New-Object System.Data.DataSet;
$SqlAdapter.Fill($DataSet);
$DataSetTable = $DataSet.Tables["Table"];
## ----------  Excel ---------- ##

## - Create an Excel Application instance:
$xlsObj = New-Object -ComObject Excel.Application;

## - Create new Workbook and Sheet (Visible = 1 / 0 not visible)
$xlsObj.Visible = 0;
$xlsWb = $xlsobj.Workbooks.Add();
$xlsSh = $xlsWb.Worksheets.item(1);

## - Build the Excel column heading:
[Array] $getColumnNames = $DataSetTable.Columns | Select ColumnName;

## - Build column header:
[Int] $RowHeader = 1;
foreach ($ColH in $getColumnNames)
{
$xlsSh.Cells.item(1, $RowHeader).font.bold = $true;
$xlsSh.Cells.item(1, $RowHeader) = $ColH.ColumnName;
$RowHeader++;
};

## - Adding the data start in row 2 column 1:
[Int] $rowData = 2;
[Int] $colData = 1;

foreach ($rec in $DataSetTable.Rows)
{
foreach ($Coln in $getColumnNames)
{
## - Next line convert cell to be text only:
$xlsSh.Cells.NumberFormat = "@";

## - Populating columns:
$xlsSh.Cells.Item($rowData, $colData) = `
$rec.$($Coln.ColumnName).ToString();
$ColData++;
};
$rowData++; $ColData = 1;
};

## - Adjusting columns in the Excel sheet:
$xlsRng = $xlsSH.usedRange;
$xlsRng.EntireColumn.AutoFit();

## ---------- Saving file and Terminating Excel Application ---------- ##

## - Saving Excel file - if the file exist do delete then save
$xlsFile = `
"C:\Temp\dbResults_$((Get-Date).ToString("yyyymmddhhmmss")).xls";

if (Test-Path $xlsFile)
{
Remove-Item $xlsFile
$xlsObj.ActiveWorkbook.SaveAs($xlsFile);
}
else
{
$xlsObj.ActiveWorkbook.SaveAs($xlsFile);
};

## Quit Excel and Terminate Excel Application process:
$xlsObj.Quit(); (Get-Process Excel*) | foreach ($_) { $_.kill() };

## - End of Script - ##

我想用单个脚本创建ApplePhone.dat和AppleGear.dat。

帮我编辑代码。

0 个答案:

没有答案