如何使用PowerShell检查SQL Server 2008 R2数据库是否存在

时间:2014-09-26 13:00:03

标签: sql powershell sql-server-2008-r2

我有一个完美的数据库脚本,但我遇到了一个问题,我需要一个if语句来检查用户指定的数据库是否已经存在。如果是,那么脚本应该创建它的备份,如果它不存在,那么脚本应该显示错误。

这是我的剧本

#Loads Assembly
[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") "(local)"
$bkdir = "C:\DBbackups" #We define the folder path as a variable 
$database = Read-Host "Please Specify Database Name"
$dbs = $server.Databases

#To Backup one Database specify exact name
#To backup multiple database which starts with same name use "*" 
foreach ($db in $dbs) 
{
 if($db.Name -like $database) 
 {
 $dbname = $db.Name
 $dt = get-date -format yyyyMMddHHmmss #We use this to create a file name based on the timestamp
 $dbBackup = new-object ("Microsoft.SqlServer.Management.Smo.Backup")
 $dbBackup.Action = "Database"
 $dbBackup.Database = $dbname
 $dbBackup.Devices.AddDevice($bkdir + "\" + $dbname + "_db_" + $dt + ".bak", "File")
 $dbBackup.SqlBackup($server) 
 write-host "Database backup is successful for"$dbname
 write-host "."
 write-host "New Backup file is"$dbname"_db_"$dt".bak"
 }
 }

 write-host "New Backup Location is" $bkdir

这是我修改为

的内容
 foreach ($db in $dbs) 
{


 if($db.Name -like $database) 
 {
 $dbname = $db.Name
 $dt = get-date -format yyyyMMddHHmmss #We use this to create a file name based on the timestamp
 $dbBackup = new-object ("Microsoft.SqlServer.Management.Smo.Backup")
 $dbBackup.Action = "Database"
 $dbBackup.Database = $dbname
 $dbBackup.Devices.AddDevice($bkdir + "\" + $dbname + "_db_" + $dt + ".bak", "File")
 $dbBackup.SqlBackup($server) 
 write-host "Database backup is successful for"$dbname `n

 write-host "New Backup file is"$dbname"_db_"$dt".bak" `n

 }
else {
write-host "invalid"
}
}

1 个答案:

答案 0 :(得分:1)

尝试在if($ db.Name -like $ database)块中添加else

if ($db.Name -like $database) { # do current backup stuff }
else { write-output "Database doesn't exist" }