如何在Powershell中避免使用SMO对象的系统数据库?

时间:2019-04-24 06:12:34

标签: sql-server powershell backup

在Powershell中使用SMO对象进行备份时如何避免使用系统数据库

我正在尝试使用系统数据库以外的所有可用数据库。

param(
$serverName,
$backupDirectory,
$daysToStoreBackups
)

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoExtended") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.ConnectionInfo") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoEnum") | Out-Null

$server = New-Object ("Microsoft.SqlServer.Management.Smo.Server") $serverName
$dbs = $server.Databases
foreach ($database in $dbs)
{
$dbName = $database.Name

$timestamp = Get-Date -format yyyy-MM-dd-HHmmss
$targetPath = $backupDirectory + "\" + $dbName + "_" + $timestamp + ".bak"

$smoBackup = New-Object ("Microsoft.SqlServer.Management.Smo.Backup")
$smoBackup.Action = "Database"
$smoBackup.BackupSetDescription = "Full Backup of " + $dbName
$smoBackup.BackupSetName = $dbName + " Backup"
$smoBackup.Database = $dbName
$smoBackup.MediaDescription = "Disk"
$smoBackup.Devices.AddDevice($targetPath, "File")
$smoBackup.SqlBackup($server)

"backed up $dbName ($serverName) to $targetPath"
}

该脚本的引用为SMO Object Backup Script Link for PS

1 个答案:

答案 0 :(得分:0)

更改此

foreach ($database in $dbs)

收件人

foreach ($database in $dbs | where { $_.IsSystemObject -eq $False })

这应该可以解决问题。