LoginSignup
1
6

More than 3 years have passed since last update.

PowerShellでMicrosoft SQL Serverへ接続し、テーブル一覧を取得する。

Posted at

PowerShellでMicrosoft SQL へ接続し、DBのデータを取得する必要がありましたので作成しました(ほぼ、自分への覚書用として…)

内容としてはデータベースへ接続し、DBのテーブル一覧を取得するというものです。

注意点(はまったこと)

 1.「テーブル一覧取得クエリ定義」の部分で、DBを明示的に指定しないと意図しないDBのリストを取得するので注意。
 2.本来であればDBへの接続情報は2つ記述する必要はないのですが、DB接続用の情報ではSQLの実行がうまくいかなかった為、2つに分けました。

サンプルスクリプト

GetTableList.ps1
    #スクリプト実行パスを取得
    $CurrentDir = Split-Path $MyInvocation.MyCommand.Path


    # DB接続情報設定(SQL実行用)
    $strServer   = '<DBサーバIP>';  # サーバーを指定
    $strDatabase = '<DB名>';       # データベースを指定
    $strUserId   = '<接続ユーザ名>';    # ユーザーIDを指定
    $strPassword = '<接続パスワード>';   # パスワードを指定


    # DB接続情報設定(DBオープン用)
    $ConnectionString=New-Object -TypeName System.Data.SqlClient.SqlConnectionStringBuilder
    $ConnectionString['Data Source'] = "<DBサーバIPアドレス>"
    $ConnectionString['Initial Catalog'] = "<DB名>"
    $ConnectionString['Integrated Security']= "TRUE"


    #DB接続準備
    $SqlConnection = New-Object System.Data.SqlClient.SqlConnection($ConnectionString)
    $SqlCommand = New-Object System.Data.SqlClient.SqlCommand($TableListQuery, $SqlConnection)

    #DBスオープン
    $SqlConnection.Open()

    #テーブル一覧取得クエリ定義(※「hoge」はDB名)
    $TableListQuery="select name from hoge.dbo.sysobjects Where xtype = 'u' order by name"
    #テーブル一覧取得SQL実行
    $TableList=Invoke-Sqlcmd $TableListQuery

  #テーブルデータ一覧から1行づつテーブル名を取得する。
    foreach($oneTable in $TableList.name ){
       Write-host $oneTable
    }

    #DBクローズ
    $SqlConnection.Close()
1
6
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
1
6