参考
http://technet.microsoft.com/ja-jp/magazine/hh855069.aspx
※これをそのままコピペすると実行時エラーとなったため若干修正。
環境
win7(64bit)
PSVersion 2.0
SQLserver 2008R2
New-Object-TypeNam → New-Object -TypeNam (スペース付与)
db.ps1
# データ取得用
function Get-DatabaseData {
[CmdletBinding()]
param (
[string]$connectionString,
[string]$query,
[switch]$isSQLServer
)
if ($isSQLServer) {
Write-Verbose 'in SQL Server mode'
$connection = New-Object -TypeName System.Data.SqlClient.SqlConnection
} else {
Write-Verbose 'in OleDB mode'
$connection = New-Object -TypeName System.Data.OleDb.OleDbConnection
}
$connection.ConnectionString = $connectionString
$command = $connection.CreateCommand()
$command.CommandText = $query
if ($isSQLServer) {
$adapter = New-Object -TypeName System.Data.SqlClient.SqlDataAdapter $command
} else {
$adapter = New-Object -TypeName System.Data.OleDb.OleDbDataAdapter $command
}
$dataset = New-Object -TypeName System.Data.DataSet
$adapter.Fill($dataset)
$dataset.Tables[0]
}
# データ操作(deleteなど)用
function Invoke-DatabaseQuery {
[CmdletBinding()]
param (
[string]$connectionString,
[string]$query,
[switch]$isSQLServer
)
if ($isSQLServer) {
Write-Verbose 'in SQL Server mode'
$connection = New-Object -TypeName System.Data.SqlClient.SqlConnection
} else {
Write-Verbose 'in OleDB mode'
$connection = New-Object -TypeName System.Data.OleDb.OleDbConnection
}
$connection.ConnectionString = $connectionString
$command = $connection.CreateCommand()
$command.CommandText = $query
$connection.Open()
$command.ExecuteNonQuery()
$connection.close()
}
# localhostのデータベース:fugeに接続しselect * from table_nameを実行
Get-DatabaseData –query "select * from table_name" –isSQLServer –connectionString "Data Source=localhost;Initial Catalog=fuge;User Id=hoge;Password=poyo"