如何使用PowerShell执行.sql文件?

Sam*_*abu 69 sql sql-server powershell powershell-module

我有一个 .sql文件.我试图通过Powershell脚本传递连接字符串详细信息并调用.sql文件.

我正在搜索并想出了一个与之相关的cmdlet Invoke-sqlcmd.当我试图找到一个与SQL相对应的模块时,我在我的机器中找不到任何一个模块.

我应该在我的机器中安装任何东西(机器已经有SQL Server Management Studio 2008 R2)来获取模块,还是有简单的方法.sql使用Powershell 执行文件?

CB.*_*CB. 89

尝试查看是否存在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
Run Code Online (Sandbox Code Playgroud)

如果是这样

Add-PSSnapin SqlServerCmdletSnapin100 # here lives Invoke-SqlCmd
Add-PSSnapin SqlServerProviderSnapin100
Run Code Online (Sandbox Code Playgroud)

然后你可以做这样的事情:

invoke-sqlcmd -inputfile "c:\mysqlfile.sql" -serverinstance "servername\serverinstance" -database "mydatabase" # the parameter -database can be omitted based on what your sql script does.
Run Code Online (Sandbox Code Playgroud)

  • 对于SQL Server 2012的补充,使用SqlServerCmdletSnapin110和SqlServerProviderSnapin110进行注册. (4认同)
  • 仅供参考,因为我相信很多人都偶然发现了这个问题。使用较新版本的 SQL,他们有 sqlps。您只需将 Import-Module “sqlps” -DisableNameChecking 添加到您的脚本中 (2认同)

Mic*_*ens 41

引用在MSDN上导入SQLPS模块,

从PowerShell管理SQL Server的推荐方法是将sqlps模块导入Windows PowerShell 2.0环境.

所以,是的,您可以使用Add-PSSnapinChristian详细介绍的方法,但是欣赏推荐的sqlps模块方法也很有用.

最简单的情况假设你有SQL Server 2012:sqlps包含在安装中,所以你只需加载模块就像任何其他模块一样(通常在你的配置文件中)Import-Module sqlps.您可以检查系统上的模块是否可用Get-Module -ListAvailable.

如果你没有SQL Server 2012,那么你所需要做的就是将sqlps模块下载到你的modules目录中,这样Get-Module/Import-Module就能找到它.奇怪的是,微软并没有使该模块提供下载!然而,Chad Miller亲切地打包了必备的部件并提供了这个模块下载.在您的... Documents\WindowsPowerShell\Modules目录下解压缩并继续导入.

值得注意的是,模块方法和snapin方法并不相同.如果加载管理单元然后运行Get-PSSnapin(没有 -Registered参数,只显示已加载的内容),您将看到SQL管理单元.另一方面,如果加载sqlps模块Get-PSSnapin将不会显示加载的snapins,那么Invoke-Sqlcmd仅通过检查snapins来测试cmdlet 的各种博客条目可能会给出错误的否定结果.

2012.10.06更新

有关sqlps模块与sqlps mini-shell与SQL Server管理单元的完整故事,请查看我最近在Simple-Talk.com上发布的用于SQL Server开发人员和DBA的两部分迷你系列Practical PowerShell.根据一位读者的评论,我所拥有的地方成功地"解除了混淆"这个问题.:-)

  • 请注意,您现在可以[从MS下载SQLPS模块](http://www.microsoft.com/en-us/download/details.aspx?id=35580); 使用`PowerShellTools.msi`,有一个x86和一个x64版本. (3认同)

Bre*_*ent 5

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
Run Code Online (Sandbox Code Playgroud)


Dav*_*ant 5

以下是我的 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
    }
}
Run Code Online (Sandbox Code Playgroud)


Tim*_*ith 5

这是一种针对简单脚本的轻量级方法,不需要额外的工具/设置/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()
}
Run Code Online (Sandbox Code Playgroud)