vaspo wrote in nullzone

PowerShell scripts to work with database



Попробовал напрямую из скриптов удалять/создавать mssql базу данных, а также накатывать скрипты, как с использованием osql.exe, так и только через SMO:

Создаём, к примеру, common.ps1 (текст приведёт ниже), который впоследствии можно будет подключить в своих скриптах следующим образом:

----------my script.ps1----------
. \MyScripts\common.ps1

CreateDB "localhost" "databasename" 10
--------------------------------------

-------------MyScripts\common.ps1----------------
$CurrentDir = Split-Path $myinvocation.mycommand.path;

. $CurrentDir\TryCatch.ps1 #исходники можно взять здесь

function ExecuteSqlScripts(
    [string] $ServerName,
    [string] $DatabaseName,
    [string] $ScriptDir,
    [bool] $SkipFirstScript
)
{
    $messages = new-Object System.Collections.ArrayList
    $result = new-Object System.Collections.ArrayList

    [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | out-null
    $Server = new-object ( 'Microsoft.SqlServer.Management.Smo.Server') $ServerName
    $DB = $Server.Databases[$DatabaseName]
    
    foreach ($ScriptFileName in dir -Name -Path $ScriptDir -Include "*.sql")
    {
        #exclude first script
        if (($SkipFirstScript -eq $false) -or ($ScriptFileName.Substring(0, 3) -gt "01_"))
        {
            [void]$messages.Add("Processing sql script '$ScriptDir$ScriptFileName'`n")

            $reader=new-object System.IO.StreamReader("$ScriptDir$ScriptFileName")
            $script=$reader.ReadToEnd()
            #or use Get-Content
            Try {
                $DB.ExecuteNonQuery($script)
            } -Catch {
                [void]$messages.Add("$_`n")
                [void]$messages.Add($_.Exception)
                [void]$result.Add($messages)
                [void]$result.Add($false)
                return $result;
            } -Finally {
                $reader.Close()
            }
        }
    }
    [void]$result.Add($messages)
    [void]$result.Add($true)
    return $result
}

function ExecuteSqlScriptsWithOSql(
    [string] $ServerName,
    [string] $DatabaseName,
    [string] $ScriptDir,
    [bool] $SkipFirstScript
)
{
    $messages = new-Object System.Collections.ArrayList
    $result = new-Object System.Collections.ArrayList
    foreach ($ScriptFileName in dir -Name -Path $ScriptDir -Include "*.sql")
    {
        #exclude first script
        if (($SkipFirstScript -eq $false) -or ($ScriptFileName.Substring(0, 3) -gt "01_"))
        {
            [void]$messages.Add("Processing sql script '$ScriptDir$ScriptFileName'`n")
           
            osql -n -S "." -d "$DatabaseName" -E -i "$ScriptDir$ScriptFileName" -b | Out-String -OutVariable osqlOutput | Out-Null
           
            [void]$messages.AddRange($osqlOutput)
           
            if ($lastexitcode -and $lastexitcode -ne 0)
            {
                [void]$messages.Add("Error on execute.`n")
                [void]$result.Add($messages)
                [void]$result.Add($false)
                return $result;
            }
        }
    }
    [void]$result.Add($messages)
    [void]$result.Add($true)
    return $result
}

function IsDbExists(
  [string] $ServerName,
  [string] $DatabaseName
)
{
    [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO")  | out-null
    $Server = New-Object "Microsoft.SqlServer.Management.Smo.Server" $ServerName
    return $Server.Databases.Contains($DatabaseName)
}

function KillDb(
  [string] $ServerName,
  [string] $DatabaseName
)
{
    [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO")  | out-null
    $Server = New-Object "Microsoft.SqlServer.Management.Smo.Server" $ServerName
    $Server.KillAllProcesses($DatabaseName)
    $Server.KillDatabase($DatabaseName)
}

function CreateDB(
  [string] $ServerName,
  [string] $DatabaseName,
  [Double] $DataSize ,
  [string] $DataPath,
  [string] $LogPath
)
{
    $output = new-Object System.Collections.ArrayList
   
    [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO")  | out-null

    $Server = New-Object "Microsoft.SqlServer.Management.Smo.Server" $ServerName

    $LogicalDataFile=$DatabaseName + "_Data"
    $LogicalLogFIle=$DatabaseName + "_Log"
   
    if (!$DataPath)
    {
        $DataPath = $Server.Information.MasterDBPath
    }
    if (!$LogPath)
    {
        $LogPath = $Server.Information.MasterDBLogPath
    }
    $dataFullName= [System.IO.Path]::Combine($DataPath, $DatabaseName + "_Data.mdf")
    $logFullName= [System.IO.Path]::Combine($LogPath, $DatabaseName +  "_Log.ldf")
    $dataSize=[double]($DataSize * 1024.0)
   
    [void]$output.Add("Creating Database.....")
    [void]$output.Add("----------------------")
    [void]$output.Add("Input...")
    [void]$output.Add("Server Name : $ServerName")
    [void]$output.Add("Database Name : $DatabaseName")
    [void]$output.Add("Data Size  :  $DataSize")
    [void]$output.Add("Data File Name :  $dataFullName")
    [void]$output.Add("Log File Name : $logFullName")
   
    $DataBase = new-object ('Microsoft.SqlServer.Management.Smo.Database') ($Server, $DatabaseName)
    $FileGrowth = new-object ('Microsoft.SqlServer.Management.Smo.FileGroup') ($DataBase, "PRIMARY")
    $DataBase.FileGroups.Add($FileGrowth)
   
    $DataBaseDataFile = new-object ('Microsoft.SqlServer.Management.Smo.DataFile') ($FileGrowth, $LogicalDataFile)
    $FileGrowth.Files.Add($DataBaseDataFile)
   
    $DataBaseDataFile.FileName = $dataFullName
   
    $DataBaseDataFile.Size = [double]( $dataSize )
    $DataBaseDataFile.GrowthType = "Percent"
    $DataBaseDataFile.Growth = 25.0
    #$DataBaseDataFile.MaxSize = [double](100.0 * 1024.0)
   
    $DataBaseLogFile = new-object ('Microsoft.SqlServer.Management.Smo.LogFile') ($DataBase, $LogicalLogFIle)
    $DataBaseLogFile.FileName = $logFullName
   
    $DataBase.Create()
    [void]$output.Add("Output....")
    [void]$output.Add("Logical name of Data is $LogicalDataFile")
    [void]$output.Add("Logical name of Log is $LogicalLogFile")
    [void]$output.Add("Data File Path is $dataFullName")
    [void]$output.Add("Log file path is $logFullName")
    [void]$output.Add("Size of the file is $dataSize")
   
    return $output
}
-------------------------------------------------------------

Источник