【问题标题】:Scripting DBs backup through Powershell通过 Powershell 编写数据库备份脚本
【发布时间】:2019-02-20 21:11:53
【问题描述】:

我创建了一个 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,说它有一个工作服务器代理和工作收集功能,但它似乎不起作用。

【问题讨论】:

    标签: sql-server powershell


    【解决方案1】:

    对于作业,请使用 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
    }
    

    【讨论】:

      【解决方案2】:

      虽然 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)
      }
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-16
        • 1970-01-01
        • 1970-01-01
        • 2017-01-28
        • 2020-02-12
        • 1970-01-01
        相关资源
        最近更新 更多