即使出错,Powershell脚本也不会继续

时间:2017-06-15 15:45:17

标签: sql powershell

我做了几个小时的研究并且目前卡住了,我看了一堆文件,然后将它传递给一些书面函数,我遇到的问题是如果我要处理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"

}

1 个答案:

答案 0 :(得分:4)

您的代码报价详细。我在你的循环中看到了这个结构:

Try{

    Foreach(...){
        $dbFiles = GetDatabaseFiles -backupfile $filename #-ErrorAction Continue
    }

}
catch{
    ...
}
finally{
    write-output "script completed"
}

相反,试试这个。 -ErrorAction Stop会将非终止错误转换为终止错误。 Try / catch不适用于非终止错误。

Foreach(...){

    Try{
        $dbFiles = GetDatabaseFiles -backupfile $filename #-ErrorAction Stop
    }
    catch{

    }

}
write-output "script completed"