I am trying to catch the exceptions generated in the SQL query execution result in my log file using powershell script.
But however the code that I use below catches the exceptions in the syntax of my powershell script and not the SQL returned exceptions.
Also I would like to log the result set of my SQL script upon successful execution. How can I acheive this.
The following is my PowerShell script,
try
{
if($Windows_authentication.tostring() -eq "1"){
invoke-SqlCmd -inputfile $Script_path\script.SQL -serverinstance $Ser_name -database $Db_name -querytimeout 65535 }
else
{
invoke-SqlCmd -inputfile $Script_path\script.SQL -serverinstance $Ser_name -database $Db_name -username $Userid -password $Passwd -querytimeout 65535 }
Write-Host "script.SQL Completed execution"
}
Catch
{
$ErrorMsg = $_.Exception.Message
Out-File -InputObject "The error message is - $ErrorMsg" -Append -NoClobber -FilePath "$Script_path\log.txt"
while( $ErrorMsg.InnerException ) {
$ErrorMsg = $ErrorMsg.InnerException
write-output $ErrorMsg
Out-File -InputObject "The error message is - $ErrorMsg" -Append -NoClobber -FilePath "$Script_path\log.txt"
}
break
}