34.PowerShell--SQL Serverの使用(2)


参照先:
http://www.shangxueba.com/jingyan/105946.html
 
一、まずSqlServerCmdletSnapin 100というSnapInを使わないで、いくつかの操作の常用データのスクリプトを書きます
1.PowerShellでデータベースの表を表示する方法を読者に聞かれたため、以下は簡単な関数です.#==============================================
# SQL Server 2008 - PowerShell
#
#zivsoft
#==============================================
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
#
#zivsoft
#==============================================
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]
}

3.データベース結合文字列の構築################################################################################### ################
# www.zivsoft.com
#
############################################################################################ #######
function global:Set-SqlConnection( $Server = $(Read-Host "SQL Server Name"), $Database = $(Read-Host "Default Database"),  $UserName , $Password  )
{
    #
    if( ($UserName -gt $null) -and ($Password -gt $null)) {
        $login = "User Id = $UserName; Password = $Password"
    }
    else {
        #
        $login = "Integrated Security = True"
    }
    #
    $SqlConnection.ConnectionString = "Server = $Server; Database = $Database; $login"
}

4.別のスタイルのデータベースデータの取得#================================================
# DataTable GetDataTable(String strSQL)
#
#================================================
function global:Get-SqlDataTable( $Query = $(Read-Host " SQL "))
{
    #
    if (-not ($SqlConnection.State -like "Open")) { $SqlConnection.Open() }

    # SQLCommand
    $SqlCmd = New-Object System.Data.SqlClient.SqlCommand $Query, $SqlConnection

    $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
    $SqlAdapter.SelectCommand = $SqlCmd

    $DataSet = New-Object System.Data.DataSet
    $SqlAdapter.Fill($DataSet) | Out-Null

    $SqlConnection.Close()

    #
    return $DataSet.Tables[0]
}

二、以上は通常PowerShellがADOを通過する.NET操作データベース、以下によりクールなSQL Server統合PowerShellコマンドをリストする
まず、Invoke-Sqlcmdという重要なcmdletのヘルプ情報を見てみましょう.NAME
    Invoke-Sqlcmd

SYNOPSIS
    Runs a script. containing statements from the languages (Transact-SQL and XQuery) and commands supported by the SQL Server sqlcmd utility.

    --------------  Example 1 --------------

    C:\PS>Invoke-Sqlcmd -Query "SELECT GETDATE() AS TimeOfQuery;" - ServerInstance "MyComputer\MyInstance"

    This example connects to a named instance of the Database Engine on a computer and runs a basic Transact-SQL script.

    TimeOfQuery
    -----------
    10/7/2007 1:04:20 PM

    --------------  Example 2 --------------

    C:\PS>Invoke-Sqlcmd -InputFile "C:\MyFolder\TestSqlCmd.sql" | Out-File -filePath "C:\MyFolder\TestSqlCmd.rpt"

    This example reads a file containing Transact-SQL statements and sqlcmd commands, runs the file, and writes the output to another file. Ensure all output files are secured with the appropriate NTFS permissions.

    Output sent to TestSqlCmd.rpt.

    --------------  Example 3 --------------

    C:\PS>$MyArray = "MYVAR1='String1'", "MYVAR2='String2'"
    Invoke-Sqlcmd -Query "SELECT `$(MYVAR1) AS Var1, `$(MYVAR2) AS Var2;" -Variable $MyArray

    This example uses an array of character strings as input to the -Variable parameter. The array defines multiple sqlcmd variables. The $ signs in the SELECT statement that identify the sqlcmd variables are escaped using the back-tick (`) character.

    Var1                        Var2
    ----                        ----
    String1                     String2

    --------------  Example 4 --------------

    C:\PS>Set-Location SQLSERVER:\SQL\MyComputer\MyInstance
    Invoke-Sqlcmd -Query "SELECT GETDATE() AS TimeOfQuery;" -ServerInstance (Get-Item .)

    This example uses Set-Location to navigate to the SQL Server PowerShell provider path for an instance of the Database Engine. Then the example uses Get-Item to retrieve an SMO Server object for use as the -ServerInstance parameter of Invoke-Sqlcmd.

    TimeOfQuery
    -----------
    10/18/2007 8:49:43 PM

    --------------  Example 5 --------------

    C:\PS>Invoke-Sqlcmd -Query "PRINT N'abc'" -Verbose

    This example uses the PowerShell -Verbose parameter to return the message output of the PRINT command.

    VERBOSE: abc

    --------------  Example 6 --------------

    C:\PS>Set-Location SQLSERVER:\SQL\MyComputer\DEFAULT\Databases\AdventureWorks
    Invoke-Sqlcmd "SELECT DB_NAME() AS DatabaseName;"

    This examples uses a positional string to supply the input to the -Query parameter. It also shows how Invoke-Sqlcmd uses the current path to set the database context to AdventureWorks.

    WARNING: Using provider context. Server = MyComputer, Database = AdventureWorks.

    DatabaseName
    ------------
    AdventureWorks

この助けをよく読んでみると、上のすべてが正しいことに気づきました.NET FrameworkでADO.NETの操作はすべてInvoke-Sqlcmdで代用でき、非常に簡潔で便利です.
たとえば、ホームデータ内のすべてのユーザーテーブルを取得するには、次のようにします.Invoke-Sqlcmd -Query "use home;SELECT name as tablename from sysobjects where xtype='U'" -QueryTimeout 3 | ft -auto
たとえば、homeデータベースのuserinfoテーブルの内容を表示します.Invoke-Sqlcmd -Query "use home;SELECT * from UserInfo" -QueryTimeout 3 | ft - auto
916x203
最後に、SQL Server 2008のManagement StudioでPowerShellを直接開くと、Invoke-Sqlcmdのようなcmdletsを直接操作できますが、Management Studioがなければどうしますか?
簡単で、Add-PSSnapin SqlServer CmdletSnapin 100で簡単にできます.