概要
PowerShellからSQLServerへ接続、データを取得します
SQLServerへ接続
# 接続情報設定 $strServer = 'localhost'; # サーバーを指定 $strDatabase = 'MyTest'; # データベースを指定 $strUserId = 'xx'; # ユーザー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, sex 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("sex")) } } catch { Write-Output $Error[0].Exception.Message } finally { $cnn.Close() $cnn.Dispose() }
- 作者:Lee Holmes
- 発売日: 2008/10/23
- メディア: 大型本