Quantcast
Viewing all articles
Browse latest Browse all 21975

try/catch in a foreach loop problem

 

Hi.

 

I'm having trouble with try/catch in a foreach loop. I'm trying to get my ps1 to run a SQL script but only against servers it can connect to. Here's what I've done so far; if I don’t use a foreach loop and just point it at one server it works fine…

 

$server = "SQL01"

 

try

{

invoke-sqlcmd -ServerInstance $server -Query "SELECT @@VERSION" -QueryTimeout 65535 -ea silentlycontinue

}

catch

{

   $_ | Out-Null

   Write-Host "Error connecting to server " $server

}

 

As SQL01 is not currently running, I get Error connecton to server SQL01 returned which is what I want. So next I'm trying to run this in a loop against a list of servers ( well two to be precise, SQL01 which isn't running and SQL02 which is)  here is the script to try and do so:-

 

 $file = "get_version.sql"

$path = "D:\PowerShell\DBA\"

 

cd $path

 

$server = (get-content $path\serverlist_test.txt | ? {!$_.Contains("#")})

foreach ($srv in $server)

{

try

 

{invoke-sqlcmd -ServerInstance $server -input $path\$file -QueryTimeout 65535 -ea silentlycontinue }

 

catch

{

                   $_ | Out-Null

                  Write-Host "Error connecting to server " $server

}

}

 

But when I run it I always get the message Error connection to server SQL01 SQL02. I know I have, but am not sure where I've gone wrong here.

 

Thanks


Viewing all articles
Browse latest Browse all 21975

Trending Articles