I have a function that I pass a server name to, then select some data from that server and insert it into a table on a centralized server. The list of servers is generated from a centralized server that isn't always up to date, and I would like for it to keep processing and log any errors that occur. However, my try-catch block doesn't seem to capture any errors.
I saw this question and tried that, and I still can't capture the errors. Here's a generic version of my function:
function Get-QueryData
{
[CmdletBinding()]
param
(
[string] $server
)
$QuerySelect = "select * from dbo.Table"
try
{
$results = Invoke-Sqlcmd -ServerInstance $server `
-Database TheDatabase `
-Query $QuerySelect `
-QueryTimeout 20 `
-OutputSqlErrors $True `
-ConnectionTimeout 5 `
-ErrorAction Stop
}
catch
{
#to-do: log error
Write Host " An error occurred trying to get query info"
}
# remaining function inserts into central server, this part doesn't fail
# unless the first part fails
}
The error I get:
Invoke-Sqlcmd: A network-related or instance-specific error occurred while establishing a connection to SQL Server... CategoryInfo: InvalidOperations (:) [Invoke-SqlCmd] SqlException FullQualifiedErrorId : SqlExecutionError,Microsoft.SqlServer.Management.Powershell.GetScriptCommand
The reason I'm getting this error is that the server was stood up, and then had to be rebuilt, but it was already added to our central management server. I can't rely on this being cleaned up right away so I need the powershell to log the error and keep moving.
Output from $PsVersionTable.PSVersion
Major - 5
Minor - 1
Build - 14409
Revision - 1012