如何使用PowerShell在批次上拆分文件

时间:2013-09-18 14:56:04

标签: sql powershell

如何使用PowerShell在批次上拆分文件?

我有一个包含多个批次的sql post部署文件。下面是我的postDeployment.sql文件的示例。

IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'StoredProc') AND type in (N'P', N'PC'))
BEGIN
    DROP PROCEDURE [dbo].[StoredProc]
END

** GO **

CREATE PROCEDURE [dbo].[StoredProc]
    @nodeId int = 0 

AS
BEGIN
    SET NOCOUNT ON;
END

**GO**

IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'StoredProc') AND type in (N'P', N'PC'))
BEGIN
    DROP PROCEDURE [dbo].[StoredProc]
END

**GO**

CREATE PROCEDURE [dbo].[StoredProc]     
    @nodeId int = 0 
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
END

$ _

我需要自己执行每个批次。 Shile分裂突出显示** GO **

我的PS命令如下(工作不正常):

function GetSqlBatchesFromString($file)
{
    $buffer = new-object System.Text.StringBuilder
    switch -regex -file $file {

        "^\s*GO[\s\d]*$" 
            { 
               # $__ returns go
                $buffer.ToString(); 
                $buffer.Length = 0;
            }
        default 
            { 
            $temp = $buffer.AppendLine($_);
            } 
        }

    $buffer.ToString();
}

function ExecuteBatch($batch)
{
Write-Host "Batch part ==== start"
Write-Host $batch
Write-Host "Batch part ==== end"   
}

 GetSqlBatchesFromString "D:\PostDeployment.sql" | % { ExecuteBatch $__}

3 个答案:

答案 0 :(得分:1)

这样:

$a = ( [system.io.file]::ReadAllText( "c:\file.sql" ) -split '(?:\bGO\b)' ) | 
% { $_ + "`r`nGO" }

创建一个包含批处理的数组,然后您可以尝试:

$a | % { ExecuteBatch $__}

答案 1 :(得分:0)

我找到了解决方案,但它并未涵盖所有案例,例如在sql中的GO:

$file = "D:\PostDeployment.sql"

  $SQLCommandText = @(Get-Content -Path $file) # loads content
    foreach($SQLString in  $SQLCommandText) 
    { 

        if($SQLString -ne "go") # if string is not equal to go then add it to existing string
        { 
            #Preparation of SQL packet 
            $SQLPacket += $SQLString + "`n" 
        } 
        else 
        { 
            Write-Host "---------------------------------------------" 
            Write-Host "Executed SQL packet:" 
            Write-Host $SQLPacket 

            $SQLPacket = ""  # clear up sql string
        } 
    } 

答案 2 :(得分:0)

function Get-SqlBatchesFromFile {
    param($file)

    $accumulate = @()

    foreach($line in (get-content $file)){
        if($line -match "^\*\*\s?GO") {        
            $accumulate -join "`r`n"
            $accumulate = @()
        } else {
            $accumulate+=$line
        }
    }
}

filter Invoke-ExecuteBatch {
    Write-Host "Batch part ==== start"
    Write-Host $_
    Write-Host "Batch part ==== end"   
}

Get-SqlBatchesFromString  C:\temp\test.sql | Invoke-ExecuteBatch