2015-10-15 161 views
0

工作在另一個腳本的工作,我試圖讀取只包含一列數據的CSV。然後在查詢SQL數據庫時,爲每個項目查找相應的ID。然後把結果(ID1,CSVID1)放入一個excel文件(我有這部分工作正常)。Powershell/SQL Server /導入CSV

現在我遇到了如何在foreach循環中填充數據集的問題。

$excelAssets = Import-Csv .\test.csv -Header assetId | Foreach-Object { 
    $assetId = $_.assetId 
    # SQL Query Variables 
    $query = "SELECT AssetId AS AssetID, BrandId AS BrandID FROM [AssetLibrary_BrandAsset] WHERE AssetId = $assetId" 

    $connection = New-SqlConnection -Server $dataSource -Database $dataBase 

    #Execute the SQL commands and place the results in dataset 
    if ($connection.State -eq 'Open') 
    { 
     $swLap = Start-Elapsed $sw "Executing SQL Query" 
     Write-Verbose "$query"; 
     $dataSet += Invoke-SQLQuery -connection $connection -query $query -ExecutionTimeout '0' 
     $i++ 
     $connection.Close(); 
     End-Elapsed $sw $swLap  
    } ELSE { 
     Write-Error "$($(Format-Elapsed $swLap)) SQL Connection Not Open - Exiting..."; 
     exit; 
    } 
} 

現在$dataSet +=不工作,我用Google搜索了無數次,試圖找到這個問題的答案的問題。任何幫助表示讚賞。

使用$dataSet

$dataTable = new-object "System.Data.DataTable" "Results" 
$dataTable = $dataSet.Tables[0] 

$rowDT = $dataTable.Rows.Count; 
$colDT = $dataTable.Columns.Count; 
Write-Host -NoNewLine "$(Format-Elapsed $sw.Elapsed) Rows: "; 
Write-Host -NoNewLine "$($rowDT+1)" -ForegroundColor "Green"; 
Write-Host -NoNewLine " Columns: " 
Write-Host -NoNewLine "$($colDT+1)" -ForegroundColor "Green"; 
Write-Host -NoNewLine " Cells: " 
Write-Host "$(($colDT+1)*($rowDT+1))" -ForegroundColor "Green"; 


#Create a 2D Array of the DataTable 
# http://stackoverflow.com/questions/13184191/fastest-way-to-drop-a-dataset-into-a-worksheet 
$tableArray = New-Object 'object[,]' $rowDT, $colDT; 
$swLap = Start-Elapsed $sw "DataTable transformation" 
# i = row and j = column 
for ($i=0;$i -lt $rowDT; $i++) 
{ 
    #Write-Progress -Activity "Transforming DataTable" -status "Row $i" -percentComplete ($i/$rowDT*100) 
    for ($j=0;$j -lt $colDT; $j++) 
    { 
     $tableArray[$i,$j] = $dataTable.Rows[$i].Item($j).ToString(); 
    }  
} 

End-Elapsed $sw $swLap 

$rowOffset = 1; $colOffset = 1;# 1,1 = "A1" 

# Write out the header column names 
for ($j=0;$j -lt $colDT; $j++) 
{ 
    $ActiveWorksheet.cells.item($rowOffset, $j+1) = $dataTable.Columns[$j].ColumnName; 
} 
$headerRange = $ActiveWorksheet.Range($ActiveWorksheet.cells.item($rowOffset, $colOffset), $ActiveWorksheet.cells.item($rowOffset, $colDT+$colOffset-1)); 
$headerRange.Font.Bold = $false 
$headerRange.Interior.Color = $headingColour 
$headerRange.Font.Name = $headingFont 
$headerRange.Font.Color = $headingFontColour 

$rowOffset++; 

# Extract the data to Excel 
$tableRange = $ActiveWorksheet.Range($ActiveWorksheet.cells.item($rowOffset, $colOffset), $ActiveWorksheet.cells.item($rowDT+$rowOffset-1, $colDT+$colOffset-1)); 
$tableRange.Cells.Value2 = $tableArray; 

# Resize the columns in Excel 
$swLap = Start-Elapsed $sw "Resize Excel Worksheet" 
$wholeRange = $ActiveWorksheet.UsedRange 
$wholeRange.EntireColumn.AutoFit() | Out-Null 
End-Elapsed $sw $swLap 

# Save Excel workbook 
$ActiveWorkbook.SaveAs("$OutputFile") 
$ActiveWorkbook.Close() 
+0

它做什麼而不是工作? –

+0

如果我將'$ dataSet + ='更改爲'$ dataSet =',它將運行該腳本,但excel文件中的輸出只是foreach循環的最後一個對象。 –

回答

1

分配給$dataSet後的第一次,它的類型很可能是陣列,這意味着運營商+=不會做出你期望的那樣。

您可以初始化$dataSet爲空數組開始分配給它之前:

Import-Csv .\test.csv -Header assetId | Foreach-Object -Begin {$dataSet = @()} -Process { 
    # rest of script in here 
} -End {return $dataSet} 

,或者你可以將其丟在分配:

[array]$dataSet += Invoke-SQLQuery -connection $connection -query $query -ExecutionTimeout '0' 

最後,另一種解決方案是確保將Invoke-SQLQuery的輸出視爲陣列,然後再將其分配給$dataSet

$dataSet += @(Invoke-SQLQuery -connection $connection -query $query -ExecutionTimeout '0') 

無論適合您的編碼風格。

+0

當我使用任何這些它仍然只輸出1行。 日誌文件:'00:01.26行:2列:3個單元格:6' –

+0

@BradleyScott您能顯示整個腳本嗎?您發佈的代碼片段中沒有任何地方會對所產生的$ dataSet變量做任何事情 –

+0

@MathiasRJessen我已經添加了在原始文章中使用'$ dataSet'的位置。 –