Technical Article

Testing all Linked Servers in all SQL SERVER servers with Powershell

,

This scripts "walk" in all servers, previously registered in one txt and search for linked servers in every server and test them.Because testconnection method in SMO does not return values just an error, i use the "trap" to insert the linked server with error.

This script use SQLPS minishell of sql server 2008 and one job step powershell. If want to use powershell shell, it is necessary load the snapins for sql server.

First create a txt with all servers and save in a folder (i use C:\dadosps\servers.txt)..something like that

Server1

Server2

Server3\Instance1

And save with name servers.txt

Create repository table in a server repository. I call "SERVER1\MSSQLSERVER_1" and database is "DBA"

This table will have the information about the linked servers with error in all servers.

Finally, we can use this script or save in .ps1

How can i say, i use this script since last year when i did it, its works fine and i call it in a sql server 2008 job step with powershell type.

--Create table repository SQL SERVER 
Create table tb_LinkedServersError
(server varchar(50),
dated datetime,
NameLinkedServer varchar(100),
ErrorMSG varchar(500)
) 

 
 

 

--Script PS 



[reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") | out-null 

$datas = [datetime] get-date -format "yyyy-MM-dd hh:mm:ss" 

##########################################################
#Dabatase and Server repository
########################################################## 

$ServidorCentral = "SERVER1\MSSQLSERVER_1"
$DatabaseCentral = "DBA" 

$sql = "truncate table tb_LinkeDServersError"
Invoke-Sqlcmd -ServerInstance $ServidorCentral -Database $DatabaseCentral -Query $sql 

foreach ($svr in get-content "C:\dadosps\servers.txt" )
{ 

 $Servidor=New-Object "Microsoft.SqlServer.Management.Smo.Server" "$svr"
 $data = $Servidor.linkedservers| where-object {$_.State -eq "Existing"} | foreach {
 trap [Exception] { 
 $erro = $_.Exception.Message
 $sql1 = "insert into tb_LinkedServersError(server,dated,NameLinkedServer,ErrorMSG) values ('$svr','$datas','$NomeLinkedServer','$erro')"
 Invoke-Sqlcmd -ServerInstance $ServidorCentral -Database $DatabaseCentral -Query $sql1
 continue; 
 }
 $NomeLInkedServer = $_.name
 $_.testconnection() 

 } 

}

Rate

5 (2)

You rated this post out of 5. Change rating

Share

Share

Rate

5 (2)

You rated this post out of 5. Change rating