PowerShell早在SQL Server 2005裡就已經被整合了, 而我第一次用卻在SQL Server 2008中。今天有 空總結幾個實際例子出來。歡迎這方面專家來完善一下:
一、先不用SqlServerCmdletSnapin100這個SnapIn來寫幾個操作常用資料的指令碼
1. 由於有讀者問如何用PowerShell顯示資料庫中表,以下是一個簡單函數供參考
#==============================================
# SQL Server 2008 - PowerShell
# 顯示使用者表
# <c>zivsoft</c>
#==============================================
function ShowCustomizedDataTable{
$SQLSERVER=read-host "Enter SQL Server Name:"
$Database=read-host "Enter Database Name:"
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$CnnString = "Server=$SQLSERVER;Database=$DATABASE;Integrated Security=True"
$SqlConnection.ConnectionString = $CnnString
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = "select name from sysobjects where type='u'"
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$SqlConnection.Close()
$DataSet.Tables[0]
}
2. 顯示SQL查詢出來的資料
#==============================================
# SQL Server 2008 - PowerShell
# 顯示查詢資料內容
# <c>zivsoft</c>
#==============================================
function Get-DataTable([string]$query)
{
$dataSet= new-object "System.Data.DataSet" "DataSetName"
$da = new-object "System.Data.SqlClient.SqlDataAdapter" ($query, $CnnString)
[void] $da.Fill($dataSet)
return $dataSet.Tables[0]
}