I have a script that I'm trying to run in TeamCity, essentially I want to force an exit code if an error happens.
Here's the script:
$s ="kbullen-865";$db_name ="tempdb";$ExceptionMessage ="";##Add-Type -Path "C:\Program Files (x86)\Microsoft SQL Server\100\SDK\Assemblies\Microsoft.SqlServer.Smo.dll"[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO')|Out-Null$serv =New-ObjectMicrosoft.SqlServer.Management.SMO.Server($s)FunctionCheckObject{Param( $DatabaseName, $ObjectSchema, $ObjectName) $scon =New-ObjectSystem.Data.SqlClient.SqlConnection#$scon.ConnectionString = "SERVER=" + $s + ";DATABASE=" + $DatabaseName + ";Integrated Security=true" $scon.ConnectionString="SERVER=$s;DATABASE=$db_name;Integrated Security=true" $trycmd =New-ObjectSystem.Data.SqlClient.SqlCommand## We refresh the object with the schema.table $trycmd.CommandText="EXECUTE sys.sp_refreshsqlmodule '$ObjectSchema.$ObjectName'" $trycmd.Connection= $scontry{ $scon.Open() $trycmd.ExecuteNonQuery()|Out-Null}catch[Exception]{ $CurrentException = $_.Exception.Message-replace "'","''"; $ExceptionMessage = $ExceptionMessage + $CurrentException;#Write-Host $DatabaseName"."$ObjectSchema"."$ObjectName ":"#Write-Host $_.Exception.MessageWrite-Host $CurrentException;}finally{ $scon.Close() $scon.Dispose()}}$db = $serv.Databases[$db_name];foreach($proc in $db.StoredProcedures|Where-Object{$_.IsSystemObject-eq $false}){ $o = $proc.Name $sc = $proc.SchemaCheckObject $db.Name $sc $o }foreach($trig in $db.Triggers|Where-Object{$_.IsSystemObject-eq $false}){ $o = $trig.Name $sc = $trig.SchemaCheckObject $db.Name $sc $o}foreach($udf in $db.UserDefinedFunctions|Where-Object{$_.IsSystemObject-eq $false}){ $o = $udf.Name $sc = $udf.SchemaCheckObject $db.Name $sc $o}foreach($view in $db.Views|Where-Object{$_.IsSystemObject-eq $false}){ $o = $view.Name $sc = $view.SchemaCheckObject $db.Name $sc $o}if($ExceptionMessage){Write-Host $ExceptionMessage;exit1;}
The
code appears to work, I get values written to the host by the line
Write-Host $CurrentException. But at the end, the $ExceptionMessage
appears empty.
What am I doing wrong?