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:[code="other"]$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-Object Microsoft.SqlServer.Management.SMO.Server($s)Function CheckObject{ Param ( $DatabaseName, $ObjectSchema, $ObjectName) $scon = New-Object System.Data.SqlClient.SqlConnection #$scon.ConnectionString = "SERVER=" + $s + ";DATABASE=" + $DatabaseName + ";Integrated Security=true" $scon.ConnectionString = "SERVER=$s;DATABASE=$db_name;Integrated Security=true" $trycmd = New-Object System.Data.SqlClient.SqlCommand ## We refresh the object with the schema.table $trycmd.CommandText = "EXECUTE sys.sp_refreshsqlmodule '$ObjectSchema.$ObjectName'" $trycmd.Connection = $scon try { $scon.Open() $trycmd.ExecuteNonQuery() | Out-Null } catch [Exception] { $CurrentException = $_.Exception.Message -replace "'", "''"; $ExceptionMessage = $ExceptionMessage + $CurrentException; #Write-Host $DatabaseName"."$ObjectSchema"."$ObjectName ":" #Write-Host $_.Exception.Message Write-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.Schema CheckObject $db.Name $sc $o }foreach ($trig in $db.Triggers | Where-Object {$_.IsSystemObject -eq $false}){ $o = $trig.Name $sc = $trig.Schema CheckObject $db.Name $sc $o}foreach ($udf in $db.UserDefinedFunctions | Where-Object {$_.IsSystemObject -eq $false}){ $o = $udf.Name $sc = $udf.Schema CheckObject $db.Name $sc $o}foreach ($view in $db.Views | Where-Object {$_.IsSystemObject -eq $false}){ $o = $view.Name $sc = $view.Schema CheckObject $db.Name $sc $o}if ($ExceptionMessage){ Write-Host $ExceptionMessage; exit 1;} [/code]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?
↧