Script to check all your linked server connections for SQL Server

By:   |   Comments (3)   |   Related: 1 | 2 | 3 | 4 | > Linked Servers


You need to quickly check all linked server connections for a given instance or list of instances.


Using Powershell and a Central Management Server you can quickly check your linked servers for connectivity.

Checking your connections

Every now and then you may have the need to check and verify that all of your defined linked servers are able to provide basic connectivity. You will most often find yourself needing to check these linked server definitions usually in between the time a server has been rebuilt after a disaster event and the time you turn it back over to your end users for them to test their systems. Having a script to quickly cursor through and check each definition comes in handy as it can save you headaches later when users complain about their systems not working.

It is not uncommon, especially as servers get older, to have more than a handful of linked servers defined. And these links could point to a variety of sources, and require a variety of specific drivers to be loaded onto your instance. As such, it is quite possible that as time passes, and systems pass from one person to another to administer, that the details of the installations can be lost. The last thing you want to do after a disaster is to hand over a server that is simply not ready.

Another use for this script would be for routine checks to make sure that your links are still valid, and to clean up ones that are no longer working. It is always better to have only those linked servers defined that are necessary, rather than to simply continue to carry forward a host of definitions that are no longer valid. This script works against SQL 2005 and SQL 2008 instances.

$OutputFile = "C:\LinkedServerFail.txt"
"Starting linked server connectivity test..." | Out-File $OutputFile 
$CMSGroup = Set-Location "SQLSERVER:\SQLRegistration\Central Management Server Group\YourCMSInstance\YourCMSDirectory\"
$InstanceListFromCMS = dir $CMSGroup -recurse | where-object { $_.Mode.Equals("-") } | select-object Name -Unique
foreach ($InstanceName in $InstanceListFromCMS) 
 $InstanceNameFriendly = (Encode-SqlName $InstanceName.Name) 
 $InstanceNameFriendly = (Decode-SqlName $InstanceNameFriendly) 
 $s = new-object ('Microsoft.SqlServer.Management.Smo.Server') $InstanceNameFriendly
 $LSName = $s.linkedservers | where-object {$_.State -eq "Existing"}
 "Cannot connect to server $InstanceNameFriendly." | Out-File $OutputFile -Append
 foreach ($Name in $LSName)
  if ($Name -ne $null)
    $Connectivity = $true
    $Connectivity = $false
    "$InstanceNameFriendly $Name connection failure." | Out-File $OutputFile -Append

The above script will output to a text file located at "C:\LinkedServerFail.txt", feel free to place the output file anywhere you want. You will also need to substitute the name of the instance where your CMS is registered (YourCMSInstance) as well as the directory for the servers you want to check. If you do not include a directory it will return all server instances resgitered in the CMS.

For example: $CMSGroup = Set-Location "SQLSERVER:\SQLRegistration\Central Management Server Group\SQL252\SQL2008\Test\"  

SQL252 is the name of my CMS instance. I have a directory named SQL2008 and a sub-directory named Test. The script will enumerate the servers registered and assigned to the directory and the script will connect to each server name and then attempt to test the connection for each linked server that is defined.

To execute the script, save it to a file with a .ps1 extension. For example, you could save it to c:\run.ps1. Open up a command prompt, navigate to the folder where the .ps1 files exists and run the following command:

C:> sqlps c:\run.ps1

The output will be written to a file that you can use to further investigate your linked server connections.

Next Steps

sql server categories

sql server webinars

subscribe to mssqltips

sql server tutorials

sql server white papers

next tip

About the author
MSSQLTips author Thomas LaRock Thomas LaRock is a Head Geek at SolarWinds and a Microsoft Certified Master, Microsoft Data Platform MVP, VMware vExpert, and a former Microsoft Certified Trainer with over 20 years’ experience.

This author pledges the content of this article is based on professional experience and not AI generated.

View all my tips

Comments For This Article

Monday, January 11, 2021 - 12:07:07 AM - CHOUCH PRUM Back To Top (88022)
Can you show me about Format of linked Server to Query data?!

Wednesday, March 6, 2013 - 10:53:00 AM - ramesh Back To Top (22595)


OLE DB provider 'Microsoft.Jet.OLEDB.4.0' cannot be used for distributed queries because the provider is configured to run in single-threaded apartment mode. (Microsoft SQL Server, Error: 7308)

Thursday, August 19, 2010 - 3:10:02 PM - krystian Back To Top (10064)
Another way to check linked servers connections for SQL servers defined on particular SQL instance is to used new system store procedure available in sql 2005.

Procedure located in master database 'sp_testlinkedserver' @servername

it takes one parameter @servername - linked server name.

Below is example how procedure can be used: 





create procedure [dbo].[usp_CheckLinkedServersConnectivity]

@recipients nvarchar(500) = '[email protected]', --- here you ca specify all email addresses for sending email notification

@Debug int = 1


/* procedure to check connectivity to all linked servers define on local SQL server (must be 2005 and up)

its using new system store procedure sp_testlinkedserver

Created by Krystian Szczyrba 29 June 2010


declare @Linked_Server_Name nvarchar(128)

declare @Return_Status int

declare @subject nvarchar(500)


@ErrorMessage NVARCHAR(4000),

@ErrorNumber INT,

@ErrorSeverity INT,

@ErrorState INT,

@ErrorLine INT,

@ErrorProcedure NVARCHAR(200);

set nocount on

declare Linked_Servers cursor for select srvname from master.dbo.sysservers

open Linked_Servers

FETCH NEXT FROM Linked_Servers

INTO @Linked_Server_Name



begin try

execute @Return_Status = sp_testlinkedserver @servername = @Linked_Server_Name

end try

begin catch



-- Assign variables to error-handling functions that

-- capture information for Sending Error message in email.


@ErrorNumber = ERROR_NUMBER(),

@ErrorSeverity = ERROR_SEVERITY(),

@ErrorState = ERROR_STATE(),

@ErrorLine = ERROR_LINE(),

@ErrorProcedure = ISNULL(ERROR_PROCEDURE(), '-');

-- Building the message string that will contain original

-- error information.

SELECT @ErrorMessage = 'Error Number : ' + cast(@ErrorNumber as varchar(5)) + ', Error Severity : ' + cast(@ErrorSeverity as varchar(5)) + ', Error State : ' + cast(@ErrorState as varchar(5)) + ', Error Line : ' + cast(@ErrorLine as varchar(5)) + ', Error Procedure : ' + cast(@ErrorProcedure as varchar(5))

+ 'Message: '+ ERROR_MESSAGE() + ' -- ' + @Linked_Server_Name

set @subject = 'Unable to CONNECT to linked server : ' + @Linked_Server_Name + ' from ' + @@SERVERNAME + ', check why connection is not working'

execute msdb.dbo.sp_send_dbmail @subject = @subject,

@recipients = @recipients,

@body = @ErrorMessage



FETCH NEXT FROM Linked_Servers

INTO @Linked_Server_Name


CLOSE Linked_Servers

DEALLOCATE Linked_Servers



get free sql tips
agree to terms