4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

SQLServerから取得したレコードデータをPowerShell一発でCSVファイルに出力する方法

Last updated at Posted at 2020-09-26

SQLServerから取得

業務上でSQLServerから情報を取得してCSVにするという案件が多いので、PowerShellでテンプレ化してみました。

PowerShell-7.0.3 ![SQL Server-Microsoft SQL Server 2017 (RTM-CU13-OD) (KB4483666) - 14.0.3049.1 (X64)](https://img.shields.io/badge/SQLServer-Microsoft SQL Server 2017 (RTM CU13 OD) (KB4483666) 14.0.3049.1 (X64)-brightgreen)

メインの実行ファイルです。

exec.ps1
. ".\config.ps1";
. ".\sql.ps1";
. ".\util-db.ps1";

# DBから取得
SQLServerSelect $dataSource $database $userId $password $sql;

Config系をまとめました。

config.ps1
[string]$dataSource = "localhost";
[string]$database = "Database";
[string]$userId = "sa";
[string]$password = "xxxx";

SQLだけ別ファイルで外だししました。

sql.ps1
[string]$sql = "
SELECT @@version;
";

SQLServer認証でSQLServerにアクセスしてSelect分を発行しています。CSV形式で標準出力しております。

util-db.ps1
function SQLServerSelect([string]$dataSource, [string]$database, [string]$userId, [string]$password, [string]$sql){

    # SqlConnectionStringBuilder を使用してSQL接続の設定を保存
    [System.Data.SqlClient.SqlConnectionStringBuilder]$connectionString = New-Object -TypeName System.Data.SqlClient.SqlConnectionStringBuilder;
    [object]$connectionString['Data Source'] = $dataSource;
    [object]$connectionString['Initial Catalog'] = $database;
    [object]$connectionString['User ID'] = $userId;
    [object]$connectionString['Password'] = $password;

    # DataTableを利用してSQL実行結果を一時格納
    [System.Data.DataTable]$resultsDataTable = New-Object System.Data.DataTable;

    # SQLConnection、SQLCommandを設定
    [System.Data.SQLClient.SQLConnection]$sqlConnection = New-Object System.Data.SQLClient.SQLConnection($connectionString);
    [System.Data.SQLClient.SQLCommand]$sqlCommand = New-Object System.Data.SQLClient.SQLCommand($sql, $sqlConnection);

    # データベースへ接続
    [object]$sqlConnection.Open();

    # ExecuteReaderを実行してDataTableにデータを格納
    [object]$resultsDataTable.Load($sqlCommand.ExecuteReader());

    # CSV形式で標準出力
    $resultsDataTable | ConvertTo-Csv -NoTypeInformation;

    # データベース接続解除
    [object]$sqlConnection.Close();
}

使用例

1.ps1配置場所に移動します
2.実行ポリシーを変更します
Set-ExecutionPolicy RemoteSigned -Scope Process -Force
3.実行します
.\exec.ps1 > out.csv
4.実行ポリシーを戻します
Set-ExecutionPolicy Restricted -Scope Process -Force

悪意のあるスクリプトを実行させないために実行ポリシーがデフォルトでは制限されている場合があります。
下記エラーが出力される場合は、上記使用例の2.を実行してください。戻す場合は4.となります。

.\exec.ps1 : このシステムではスクリプトの実行が無効になっているため、
ファイル ・・・.ps1 を読み込むことができません。
4
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?