通过Powershell编写脚本数据库备份

时间:2019-02-20 08:19:41

标签: sql-server powershell

我创建了一个PowerShell脚本,该脚本备份了数据库的整个结构。关于作业备份,我找不到解决方案。

$v = [System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO')
if ((($v.FullName.Split(','))[1].Split('='))[1].Split('.')[0] -ne '9')
{
    [System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMOExtended') | out-null
}
[System.Reflection.Assembly]:: LoadWithPartialName('Microsoft.SqlServer.SmoEnum') | out-null

set-psdebug -strict # catch a few extra bugs
$ErrorActionPreference = "stop"
$My = 'Microsoft.SqlServer.Management.Smo'
$srv = new-object ("$My.Server") $ServerName # attach to the server
foreach($sqlDatabase in $srv.databases)
{
    $databaseName=$sqlDatabase.name
    if ($databaseName.count)
    { 
        $scripter = new-object ("$My.Scripter") $srv # create the scripter
        $scripter.Options.ToFileOnly = $true 
        # we now get all the object types except extended stored procedures
        # first we get the bitmap of all the object types we want 
        $all =[long] 
        [Microsoft.SqlServer.Management.Smo.DatabaseObjectTypes]:: all -bxor 
       [Microsoft.SqlServer.Management.Smo.DatabaseObjectTypes]:: ExtendedStoredProcedure
        # and we store them in a datatable
        $d = new-object System.Data.Datatable
        # get everything except the servicebroker object, the information schema and system views
        $d = $srv.databases[$databaseName].EnumObjects([long]0x1FFFFFFF -band $all) | Where-Object {$_.Schema -ne 'sys'-and $_.Schema "information_schema" 
        #Saving it in a directory
    }
}

此脚本用于备份数据库,但是用于备份msdb。我研究了Microsoft.SqlServer.SMO,说它具有作业服务器代理和作业收集功能,但似乎不起作用。

2 个答案:

答案 0 :(得分:0)

对于作业,请使用JobServer.Jobs集合。您可以类似地编写其他服务器级对象的脚本。

下面是一个例子。

$jobsCollection = $srv.JobServer.Jobs
$scriptingOptions = New-Object  Microsoft.SqlServer.Management.Smo.ScriptingOptions
$scriptingOptions.IncludeIfNotExists = $true
$scriptingOptions.AppendToFile = $false
$scriptingOptions.ToFileOnly = $true

foreach ($job in $jobsCollection) {
    Write-Host "Scripting $($job.Name)"
    $scriptingOptions.FileName = "C:\ScriptFolder\Jobs.sql"
    $job.Script($scriptingOptions)
    $scriptingOptions.AppendToFile = $true
}

答案 1 :(得分:0)

尽管Dan给出的答案对我有所帮助,但这并不是在文件夹中创建脚本。它只是用作业名称创建文件夹。所以,我做了这样的事情:

  foreach($sqlDatabase in $srv.JobServer.Jobs)
  { $databaseName=$sqlDatabase.name
    write-host("I am her '$databaseName' ");
    $scripter = new-object ("$My.Scripter") $srv # create the scripter
    $scripter.Options.ToFileOnly = $true 
    $d = new-object System.Data.Datatable
    $d=$srv.JobServer.Jobs[$databaseName]
    $d| FOREACH-OBJECT { 
     trap [System.Management.Automation.MethodInvocationException]{
        write-host ("ERROR: " + $_) -Foregroundcolor Red; Continue

                }
# for every object we have in the datatable.
   $SavePath="$($DirectoryToSaveTo)\$($ServerName)\$($databaseName)\$($_.DatabaseObjectTypes)"
   # create the directory if necessary (SMO doesn't).
   if (!( Test-Path -path $SavePath )) # create it if not existing
        {Try { New-Item $SavePath -type directory | out-null } 
        Catch [system.exception]{
            Write-Error "error while creating '$SavePath' $_"
            return
         } 
    }
    # tell the scripter object where to write it
    $scripter.Options.Filename = "$SavePath\$($_.name -replace '[\\\/\:\.]','-').sql";
    # Create a single element URN array
    $UrnCollection = new-object ('Microsoft.SqlServer.Management.Smo.urnCollection')
    $URNCollection.add($_.urn)
    # and write out the object to the specified file
    $scripter.script($URNCollection)
}
    }