codememo

powershell을 사용하여 .sql 파일을 실행하는 방법은 무엇입니까?

tipmemo 2023. 7. 7. 19:04
반응형

powershell을 사용하여 .sql 파일을 실행하는 방법은 무엇입니까?

저는 있습니다.sql파일. 연결 문자열 세부 정보를 Powershell 스크립트를 통해 전달하고 호출하려고 합니다..sql파일.

검색하던 중에 다음과 관련된 cmdlet이 떠올랐습니다.Invoke-sqlcmdSQL에 해당하는 모듈을 찾으려다가 기계에 아무도 없었습니다.

모듈을 가져오려면 컴퓨터에 설치해야 합니까(기계에 이미 SQL Server Management Studio 2008 R2가 있음), 아니면 실행하기 쉬운 방법이 있습니까?.sqlPowershell을 사용한 파일?

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의 SQLPS 모듈 가져오기에서 인용,

PowerShell에서 SQL Server를 관리하는 권장 방법은 sqlps 모듈을 윈도우즈 PowerShell 2.0 환경으로 가져오는 것입니다.

그래서, 네, 당신은 그것을 사용할 수 있습니다.Add-PSSnapinChristian이 자세히 설명한 접근법이지만 권장되는 sqlps 모듈 접근법을 감상하는 것도 유용합니다.

가장 단순한 경우는 SQL Server 2012가 설치되어 있다고 가정합니다. sqlps는 설치에 포함되어 있으므로 다음을 통해 다른 모듈(일반적으로 프로필에 있음)을 로드하기만 하면 됩니다.Import-Module sqlps시스템에서 사용할 수 있는 모듈이 있는지 확인할 수 있습니다.Get-Module -ListAvailable.

SQL Server 2012가 없는 경우에는 Get-Module/Import-Module이 찾을 수 있도록 sqlps 모듈을 모듈 디렉토리에 다운로드하기만 하면 됩니다.이상하게도, Microsoft는 이 모듈을 다운로드할 수 있도록 하지 않습니다!하지만 Chad Miller는 친절하게도 필요한 부품들을 포장하여 이 모듈을 다운로드해 주었습니다.아래에서 압축을 풉니다...문서\Windows PowerShell\Modules 디렉토리를 선택하고 가져오기를 계속합니다.

모듈 접근법과 스냅인 접근법이 동일하지 않다는 점은 흥미롭습니다.스냅인을 로드하면 실행합니다.Get-PSSnapin(-Registered 매개 변수 없이 로드한 내용만 표시) SQL 스냅인이 표시됩니다.반면에 sqlps 모듈을 로드하는 경우Get-PSSnapin로드된 스냅인을 표시하지 않으므로 테스트하는 다양한 블로그 항목Invoke-Sqlcmdcmdlet은 스냅인만 검사하여 잘못된 음성 결과를 제공할 수 있습니다.

2012.10.06 업데이트

sqlps 모듈과 sqlps mini-shell 및 SQL Server 스냅인에 대한 전체 이야기를 보려면 최근 Simple-Talk.com 에 게시된 SQL Server 개발자DBA를 위한 2개의 미니 시리즈 Practical 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 서버 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")'"

언급URL : https://stackoverflow.com/questions/10894688/how-to-execute-sql-file-using-powershell

반응형