How could I do something like this in Powershell?
I've tried something like this:
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | out-null
# Create SMO Server Object
$Server = New-Object ('Microsoft.SQLServer.Management.Smo.Server') "SD-KP-DEVSUP01\KP"
#AddHandler $Server.ConnectionContext.InfoMessage, New SqlInfoMessageEventHandler(AddressOf OnInfoMessage)
$db = $Server.Databases["master"]
try {
$db.ExecuteWithResults("SELECT name from sys.databases2").Tables[0]
}
catch [Exception] {
$_.Exception|fl -Force
#[SqlException]$se=$_.Exception.InnerException
}
and I get this Error:
SmoExceptionType : FailedOperationException
Operation : Execute with results
FailedObject : [master]
Message : Execute with results failed for Database 'master'.
HelpLink : http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&ProdVer=12.0.2000.8+((SQL14_RTM).140220-1752)&EvtSrc=Microsoft.SqlServer.Management.Smo.ExceptionTemplates.FailedOperationExceptionText&EvtID=Exec
ute+with+results+Database&LinkId=20476
Data : {HelpLink.ProdName, HelpLink.BaseHelpUrl, HelpLink.LinkId, HelpLink.ProdVer...}
InnerException : Microsoft.SqlServer.Management.Common.ExecutionFailureException: An exception occurred while executing a Transact-SQL statement or batch. ---> System.Data.SqlClient.SqlException: Invalid object name
'sys.databases2'.
at Microsoft.SqlServer.Management.Common.ConnectionManager.ExecuteTSql(ExecuteTSqlAction action, Object execObject, DataSet fillDataSet, Boolean catchException)
at Microsoft.SqlServer.Management.Common.ServerConnection.ExecuteWithResults(String sqlCommand)
--- End of inner exception stack trace ---
at Microsoft.SqlServer.Management.Common.ServerConnection.ExecuteWithResults(String sqlCommand)
at Microsoft.SqlServer.Management.Common.ServerConnection.ExecuteWithResults(StringCollection sqlCommands)
at Microsoft.SqlServer.Management.Smo.ExecutionManager.ExecuteWithResults(StringCollection query)
at Microsoft.SqlServer.Management.Smo.Database.ExecuteWithResults(StringCollection sqlCommands)
TargetSite : System.Data.DataSet ExecuteWithResults(System.Collections.Specialized.StringCollection)
StackTrace : at Microsoft.SqlServer.Management.Smo.Database.ExecuteWithResults(StringCollection sqlCommands)
at CallSite.Target(Closure , CallSite , Object , String )
Source : Microsoft.SqlServer.Smo
HResult : -2146233088
I've looked at all the items in $_ and $Error[0] but can't find any reference to what actual script line failed.
I really want to do output something like this to get more details where the error happened in a big script file.
Console.WriteLine("Msg {0}, Level {1}, State {2}, Line {3}", e.Number, e.Class, e.State, e.LineNumber)