I've try, catch statement in my powershell to handling errors exception, but below statement didn't output sql error messages to .log file.
Try{
Invoke-SqlCmd -InputFile "D:\DropBoxFolder\Dropbox\Public\WIKI_POWERSHELL\AdminTask\ExecutePowerShell_From_BAT\Map_AU.sql"
}
Catch{
$ErrorMessage = $_.Exception.Message
$Time=Get-Date
"This script failed at $Time and error message was $ErrorMessage" | out-file D:\DropBoxFolder\Dropbox\Public\WIKI_POWERSHELL\AdminTask\ExecutePowerShell_From_BAT\Inovke_SQLScript.log -append
}
Finally{
$Time=Get-Date
"This script made a read attempt at $Time" | out-file D:\DropBoxFolder\Dropbox\Public\WIKI_POWERSHELL\AdminTask\ExecutePowerShell_From_BAT\Inovke_SQLScript.log -append
$con.Close()
}
Here the errors returned from powershell and I would like to redirect the errors to .log
Invoke-Sqlcmd : There is already an object named 'Map_AU234' in the database. At D:\DropBoxFolder\Dropbox\Public\WIKI_POWERSHELL\AdminTask\ExecutePowerShell_ From_BAT\Inovke_SQLScript.ps1:49 char:14 + Invoke-SqlCmd <<<< -InputFile "D:\DropBoxFolder\Dropbox\Public\WIKI_POWERSHE LL\AdminTask\ExecutePowerShell_From_BAT\Map_AU.sql" + CategoryInfo : InvalidOperation: (:) [Invoke-Sqlcmd], SqlPowerS hellSqlExecutionException + FullyQualifiedErrorId : SqlError,Microsoft.SqlServer.Management.PowerShe ll.GetScriptCommand
out-filein quotes as shown here -$Time=Get-Date "This script made a read attempt at $Time" | out-file "D:\DropBoxFolder\Dropbox\Public\WIKI_POWERSHELL\AdminTask\ExecutePowerShell_From_BAT\Inovke_SQLScript.log" -append