繁体   English   中英

即使发生错误,Powershell脚本也不会继续

[英]Powershell script will not continue even after error

我已经进行了数小时的研究,目前仍处于停滞状态,我看上去会拾取一堆文件,然后将其传递给某些书面函数,我遇到的问题是,如果要处理200个文件,我会不想让每个错误都终止脚本,因为这意味着整个事情需要再次执行。

因此,我想使用“尝试/捕获”或任何其他手段来捕获错误,以便使我知道该错误,但是我希望将循环移至下一个项目并对其进行处理。 当我在循环中删除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" } 

您的代码是冗长的引用。 我在您的循环中看到此结构:

Try{

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

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

相反,请尝试此。 -ErrorAction Stop将把非终止错误变成终止错误。 “尝试/捕获”不适用于非终止错误。

Foreach(...){

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

    }

}
write-output "script completed"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM