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