簡體   English   中英

如何使用powershell執行.sql文件?

[英]How to execute .sql file using powershell?

我有一個 。 sql文件。 我正在嘗試通過 Powershell 腳本傳遞連接字符串詳細信息並調用.sql文件。

我正在搜索並想出了一個與Invoke-sqlcmd相關的 cmdlet。 當我試圖找到一個對應於 SQL 的模塊時,我沒有在我的機器中找到任何一個。

我應該在我的機器上安裝任何東西(機器已經有 SQL Server Management Studio 2008 R2)來獲取模塊,還是有什么簡單的方法可以使用 Powershell 執行.sql文件?

嘗試查看是否存在 SQL 管理單元:

get-pssnapin -Registered

Name        : SqlServerCmdletSnapin100
PSVersion   : 2.0
Description : This is a PowerShell snap-in that includes various SQL Server cmdlets.

Name        : SqlServerProviderSnapin100
PSVersion   : 2.0
Description : SQL Server Provider

如果是這樣

Add-PSSnapin SqlServerCmdletSnapin100 # here lives Invoke-SqlCmd
Add-PSSnapin SqlServerProviderSnapin100

然后你可以做這樣的事情:

invoke-sqlcmd -inputfile "c:\mysqlfile.sql" -serverinstance "servername\serverinstance" -database "mydatabase" # the parameter -database can be omitted based on what your sql script does.

引用 MSDN 上的Import the SQLPS Module

從 PowerShell 管理 SQL Server 的推薦方法是將 sqlps 模塊導入 Windows PowerShell 2.0 環境。

所以,是的,您可以使用 Christian 詳述的Add-PSSnapin方法,但欣賞推薦的 sqlps 模塊方法也很有用。

最簡單的情況假設您擁有 SQL Server 2012:安裝中包含sqlps ,因此您只需通過Import-Module sqlps像任何其他模塊(通常在您的配置文件中)一樣加載模塊。 您可以使用Get-Module -ListAvailable檢查系統上的模塊是否可用。

如果您沒有 SQL Server 2012,那么您只需將sqlps模塊下載到您的模塊目錄中,以便 Get-Module/Import-Module 找到它。 奇怪的是,微軟沒有提供這個模塊供下載! 但是,Chad Miller 已將必要的部分打包並提供此模塊下載 將其解壓縮到您的 ...Documents\WindowsPowerShell\Modules 目錄下,然后繼續導入。

有趣的是,模塊方法和 snapin 方法並不相同。 如果加載管理單元然后運行Get-PSSnapin不帶-Registered 參數,僅顯示已加載的內容),您將看到 SQL 管理單元。 另一方面,如果您加載 sqlps 模塊Get-PSSnapin將不會顯示加載的管理單元,因此僅通過檢查管理單元來測試Invoke-Sqlcmd cmdlet 的各種博客條目可能會給出假陰性結果。

2012.10.06 更新

有關 sqlps 模塊與 sqlps mini-shell 與 SQL Server 管理單元的完整故事,請查看我最近在 Simple-Talk.com 上發布的面向 SQL Server 開發人員和 DBA 的兩部分迷你系列實用 PowerShell根據一位讀者的評論,我成功地“消除了混淆”這個問題。 :-)

if(Test-Path "C:\Program Files\Microsoft SQL Server\MSSQL11.SQLEXPRESS") { #Sql Server 2012
    Import-Module SqlPs -DisableNameChecking
    C: # Switch back from SqlServer
} else { #Sql Server 2008
    Add-PSSnapin SqlServerCmdletSnapin100 # here live Invoke-SqlCmd
}

Invoke-Sqlcmd -InputFile "MySqlScript.sql" -ServerInstance "Database name" -ErrorAction 'Stop' -Verbose -QueryTimeout 1800 # 30min

這是我的 PowerShell 配置文件中用於加載 SQL 管理單元的函數:

function Load-SQL-Server-Snap-Ins
{
    try 
    {
        $sqlpsreg="HKLM:\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.SqlServer.Management.PowerShell.sqlps"

        if (!(Test-Path $sqlpsreg -ErrorAction "SilentlyContinue"))
        {
            throw "SQL Server Powershell is not installed yet (part of SQLServer installation)."
        }

        $item = Get-ItemProperty $sqlpsreg
        $sqlpsPath = [System.IO.Path]::GetDirectoryName($item.Path)

        $assemblyList = @(
            "Microsoft.SqlServer.Smo",
            "Microsoft.SqlServer.SmoExtended",
            "Microsoft.SqlServer.Dmf",
            "Microsoft.SqlServer.WmiEnum",
            "Microsoft.SqlServer.SqlWmiManagement",
            "Microsoft.SqlServer.ConnectionInfo ",
            "Microsoft.SqlServer.Management.RegisteredServers",
            "Microsoft.SqlServer.Management.Sdk.Sfc",
            "Microsoft.SqlServer.SqlEnum",
            "Microsoft.SqlServer.RegSvrEnum",
            "Microsoft.SqlServer.ServiceBrokerEnum",
            "Microsoft.SqlServer.ConnectionInfoExtended",
            "Microsoft.SqlServer.Management.Collector",
            "Microsoft.SqlServer.Management.CollectorEnum"
        )

        foreach ($assembly in $assemblyList)
        { 
            $assembly = [System.Reflection.Assembly]::LoadWithPartialName($assembly) 
            if ($assembly -eq $null)
                { Write-Host "`t`t($MyInvocation.InvocationName): Could not load $assembly" }
        }

        Set-Variable -scope Global -name SqlServerMaximumChildItems -Value 0
        Set-Variable -scope Global -name SqlServerConnectionTimeout -Value 30
        Set-Variable -scope Global -name SqlServerIncludeSystemObjects -Value $false
        Set-Variable -scope Global -name SqlServerMaximumTabCompletion -Value 1000

        Push-Location

         if ((Get-PSSnapin -Name SqlServerProviderSnapin100 -ErrorAction SilentlyContinue) -eq $null) 
        { 
            cd $sqlpsPath

            Add-PsSnapin SqlServerProviderSnapin100 -ErrorAction Stop
            Add-PsSnapin SqlServerCmdletSnapin100 -ErrorAction Stop
            Update-TypeData -PrependPath SQLProvider.Types.ps1xml
            Update-FormatData -PrependPath SQLProvider.Format.ps1xml
        }
    } 

    catch 
    {
        Write-Host "`t`t$($MyInvocation.InvocationName): $_" 
    }

    finally
    {
        Pop-Location
    }
}

這是一種無需額外工具/設置/PowerShell 附加組件的簡單腳本的輕量級方法。

$conn = New-Object System.Data.SqlClient.SqlConnection
$conn.ConnectionString = $connectionStringGoesHere
$conn.Open()
$content = Get-Content $scriptFileNameGoesHere
$cmds = New-Object System.Collections.ArrayList
$cmd = ""
$content | foreach {
    if ($_.Trim() -eq "GO") { $cmds.Add($cmd); $cmd = "" } 
    else { $cmd =  $cmd + $_ +"`r`n" }
}
$cmds | foreach {
    $sc = New-Object System.Data.SqlClient.SqlCommand 
    $sc.CommandText = $_
    $sc.Connection = $conn
    $sc.ExecuteNonQuery()
}

使用 2008 Server 2008 和 2008 R2

Add-PSSnapin -Name SqlServerCmdletSnapin100, SqlServerProviderSnapin100

2012 年和 2014 年

Push-Location
Import-Module -Name SQLPS -DisableNameChecking
Pop-Location

Invoke-Sqlcmd -Database MyDatabase -Query "exec dbo.sp_executesql N'$(Get-Content "c:\my.sql")'"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM