2016-07-04 61 views

回答

0

TechNet文章https://technet.microsoft.com/en-us/magazine/hh855069.aspx給出瞭如何使用PowerShell連接到SQL Server數據庫的一個很好的運行。它還包括你可以在腳本中使用的例子功能:

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] 
} 
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() 
} 

在從TechNet文章上面的腳本,你只需要提供3個參數:連接字符串(你會使用受信任的連接=真集成安全性),要運行的查詢和數據庫類型(SQL Server或OleDB)。

0

另外,您還可以恢復爲功能Invoke-Sqlcmd2,它可以爲您自動完成所有這些操作。我們非常成功地使用它,它使生活變得更加輕鬆。

相關問題