需求
- 將指定的 Log 記錄,匯入資料庫,產生 row data
- 將 row data 轉換成為需要的報表資料
- 產生報表
規劃
- powershell 讀取檔案
- powershell 連接資料庫
- powershell 執行 SQL
- powershell 作 BulkInsert
- powershell 寫入檔案
簡記要點
- powershell 可以直接取用 .Net Framework 或 COM 元件
- 宣告變用要用
$
字號 #
是註解
讀取檔案
1 | #用New-Object 建立.Net StreamReader 物件 |
連線資料庫與執行語法
1 | $connection = New-Object System.Data.SQLClient.SQLConnection |
BulkInsert
- 從檔案建立 DataTable
1 | $table = New-Object System.Data.DataTable |
- 透過 BulkCopy 將 DataTable 寫入資料庫
1 | $connection.Open() |
進度條
1 | Write-Progress -Activity "BulkInsert" -Status "載入百分比: 100 %" -PercentComplete 100; |
產生報表
1 | $datatable | export-csv C:\Reports\20161026.csv -Encoding UTF8 |
參考
- https://msdn.microsoft.com/en-us/powershell
- https://msdn.microsoft.com/en-us/powershell/scripting/getting-started/cookbooks/using-static-classes-and-methods
- https://cmatskas.com/execute-sql-query-with-powershell/
- https://blogs.technet.microsoft.com/heyscriptingguy/
(fin)