0
0

More than 1 year has passed since last update.

WindowsのPowerShellメモ #2

Last updated at Posted at 2021-08-31

概要

PowerShellの環境設定ファイルを用意してそれをインクルードするサンプルを作成したいと思います。
毎回同じShellにDB関連接続情報を定義より1つのファイルに定義しておいて該当するShellにインクルードする方式です。

事前確認

スクリプトが起動されるパスの情報を取得します。
そのパスから設定ファイルを参照できるようにパスを指定します。
パス関連情報取得は次のサンプルから確認できます。

現在スクリプトのパス情報を取得

# path.ps1
$scriptPath = Split-Path $MyInvocation.MyCommand.Path

Write-Output($scriptPath +  "/")

# 実行結果
PS C:\temp>  PowerShell -ExecutionPolicy RemoteSigned  .\path.ps1
C:\temp/
PS C:\temp>

DB接続情報を定義

次のファイルにDB関連情報を定義します。

# \config\setting.ps1
#####################################
# 環境変数
#####################################
$strServer   = 'xxx.xxx.xxx.xxx';  # サーバーを指定
$strDatabase = 'xxxxx';            # データベースを指定
$strUserId   = 'xxxxx';            # ユーザーIDを指定
$strPassword = 'xxxxx';            # パスワードを指定

修正前のソース

次は修正前のソースです。

# 接続情報設定
$strServer   = 'xxx.xxx.xxx.xxx';  # サーバーを指定
$strDatabase = 'xxxxx';            # データベースを指定
$strUserId   = 'xxxxx';            # ユーザーIDを指定
$strPassword = 'xxxxx';            # パスワードを指定

$cnnstr = "Data Source=$strServer;Initial Catalog=$strDatabase;User ID=$strUserId;Password=$strPassword;"

$cnn = New-Object -TypeName System.Data.SqlClient.SqlConnection $cnnstr

try {
    $cnn.Open()
    $cmd             = $cnn.CreateCommand()
    $cmd.Connection  = $cnn
    $cmd.CommandText = "select id, name, tel from  members"
    $adpter          = New-Object -TypeName System.Data.SqlClient.SqlDataAdapter $cmd;
    $ds              = New-Object -TypeName System.Data.DataSet;

    $adpter.Fill($ds)
    $table = $ds.Tables[0]

    foreach ($row in $table.Rows) {
        Write-Output($row.item("id").tostring() + "/" + $row.item("name") + "/" + $row.item("tel"))
    }
}
catch {
    Write-Output $Error[0].Exception.Message
} finally {
    $cnn.Close()
    $cnn.Dispose()
}

修正後のソース

次は環境設定ファイルを読み込む処理に変更したソースです。

# 接続情報設定
#$strServer   = 'xxx.xxx.xxx.xxx';  # サーバーを指定
#$strDatabase = 'xxxxx';            # データベースを指定
#$strUserId   = 'xxxxx';            # ユーザーIDを指定
#$strPassword = 'xxxxx';            # パスワードを指定

#追加>>>>>>>
#現在実行ファイルのパス取得 
$scriptPath = Split-Path $MyInvocation.MyCommand.Path
#環境変数をインクルード
. ($scriptPath + '\config\setting.ps1')
#追加>>>>>>>

$cnnstr = "Data Source=$strServer;Initial Catalog=$strDatabase;User ID=$strUserId;Password=$strPassword;"

$cnn = New-Object -TypeName System.Data.SqlClient.SqlConnection $cnnstr

try {
    $cnn.Open()
    $cmd             = $cnn.CreateCommand()
    $cmd.Connection  = $cnn
    $cmd.CommandText = "select id, name, tel from  members"
    $adpter          = New-Object -TypeName System.Data.SqlClient.SqlDataAdapter $cmd;
    $ds              = New-Object -TypeName System.Data.DataSet;

    $adpter.Fill($ds)
    $table = $ds.Tables[0]

    foreach ($row in $table.Rows) {
        Write-Output($row.item("id").tostring() + "/" + $row.item("name") + "/" + $row.item("tel"))
    }
}
catch {
    Write-Output $Error[0].Exception.Message
} finally {
    $cnn.Close()
    $cnn.Dispose()
}

実行結果

次のコマンドで確認します。
前回の実行結果と同じであることが確認できます。

# コマンド
PS C:\temp>  PowerShell -ExecutionPolicy RemoteSigned  .\db1.ps1
2
test1/テスト1/123-1234-1111
test2/テスト2/111-1456-1234
PS C:\temp>

参照サイト

WindowsのPowerShellでパス文字列を操作する
https://atmarkit.itmedia.co.jp/ait/articles/0809/12/news139.html

終わりに

今回はDB接続情報を定義して各PowerShellで利用できるようにテストしました。
Windowsで基本的に提供されているPowerShellを利用して何かDB周りの処理及びアプリケーションが作成できそうですね。

0
0
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
0
0