1

如何使用powershell批量拆分文件?

我有一个包含多个批次的 sql 部署后文件。下面是我的 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 $__}
4

3 回答 3

2

这个:

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

创建一个数组,然后你可以尝试:

$a | % { ExecuteBatch $__}
于 2013-09-18T15:11:11.687 回答
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
        } 
    } 
于 2013-09-18T16:21:21.583 回答
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
于 2013-09-20T17:20:22.323 回答