您好我正在使用ps脚本备份sql数据库,但我有3 for for循环备份3数据库是否有一种方法,我有1个for循环,它采取我声明的3个变量并进行备份。这是我的代码
[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
$test1 = 'admin'
$test2 = 'contacts'
$test3 = 'humanResource'
$dbs = $server.Databases
foreach ($db in $dbs)
{
if($db.Name -like $test1)
{
$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 "New Backup file is"$dbname"_db_"$dt".bak"
write-host "New Backup Location is" $bkdir
}
}
我是否也可以使用像这样的单个if语句来完成此任务
if($db.Name -like $test1) or ($db.Name -like $test2) or ($db.Name -like
$test3)
{
$dbname = $db.Name
$dt = get-date -format yyyyMMddHHmmss
$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 "New Backup file is"$dbname"_db_"$dt".bak"
write-host "New Backup Location is" $bkdir
}
答案 0 :(得分:0)
你可以试试这个;
$array = @("admin", "contacts", "humanResource")
foreach ($element in $array) {
foreach ($db in $dbs)
{
if($db.Name -like $element)
{
$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 "New Backup file is "$dbname"_db_"$dt".bak"
write-host "New Backup Location is " $bkdir
}
}
}