【发布时间】:2017-06-15 23:53:11
【问题描述】:
我已经做了几个小时的研究,目前卡住了,我看了一下,拿起一堆文件,然后将它传递给一些书面函数,我遇到的问题是,如果我有 200 个文件要处理,我不希望每个错误都终止脚本,因为这意味着整个事情需要再次重新执行。
所以我想使用 Try/Catch 或任何其他方式来捕获错误,以便我知道它,但我希望循环移动到下一个项目并处理它。当我在循环中删除 Try..Catch 并指定 erroraction = 'continue' 时,它确实继续,但由于数据库连接仍处于打开状态,所有文件都失败了。
这里有什么想法吗?
所以目标是在循环过程中,如果文件遇到错误,只需继续下一个文件,但突出显示错误。
function GetDatabaseFiles ([STRING]$backupfile)
{
Try
{
$SQLConnection.Open()
$SQLQuery = "RESTORE FILELISTONLY
FROM DISK = N'$backupfile'
WITH NOUNLOAD"
$SQLCommand = New-Object system.Data.SqlClient.SqlCommand
$SQLCommand.CommandText = $SQLQuery
$SQLCommand.Connection = $SQLConnection
$SQLAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SQLAdapter.SelectCommand = $SQLCommand
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$SQLConnection.Close()
return $DataSet.Tables[0] | Select-Object LogicalName,PhysicalName,type
}
Catch
{
# Handle the error
$err = $_.Exception
write-host $err.Message -ForegroundColor Red
while( $err.InnerException ) {
$err = $err.InnerException
write-host $err.Message -ForegroundColor Red
LogInfo -db "Database file - $backupfile" -message "ERROR DETAILS for Getting DB Files section !!!! $err.Message"
}
if ($error) { $failedcount ++ }
}
}
[STRING]$SQLServer = $dbserver
[STRING]$SQLDatabase = 'master'
[STRING]$SQLConnectString = "Data Source=$SQLServer; Initial Catalog=$SQLDatabase; Integrated Security=True; Connection Timeout=0"
[OBJECT]$SQLConnection = New-Object System.Data.SqlClient.SqlConnection($SQLConnectString);
$files = Get-ChildItem $backup_path -Recurse | Where-Object {$_.extension -eq ".bak"} | Sort-Object $_.name
$total_count = $files.Length
Try
{
$error.clear()
# Start looping through each backup file and restoring the databases
foreach ($filename in $files) {
$filecount ++
write-host "Currently attemping to restore the backup file $filename number $filecount" -ForegroundColor "Green"
#Set the filename variable to the fullpath/name of the backup file
$filename = $filename.FullName
$dbFiles = GetDatabaseFiles -backupfile $filename #-ErrorAction Continue
$dbFiles = $dbFiles[1..$dbFiles.Length]
}
}
catch
{
# Handle the error
$err = $_.Exception
write-output $err.Message
while( $err.InnerException ) {
$err = $err.InnerException
write-output $err.Message
}
if ($error) { $failedcount ++ }
}
finally {
write-output "script completed"
}
【问题讨论】:
标签: sql powershell