Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

I had the following code in a PowerShell script:

$sql_instance = "SQLEXPRESS"
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') 
$server = New-Object ('Microsoft.SqlServer.Management.Smo.Server') $sql_instance
Write-Host $server.InstanceName

And nothing was returned. After about 20 minutes of researching I realized I forgot to include the computer name when creating the $server object.

The code should have been:

$sql_instance = "MYSERVER\SQLEXPRESS"

My question is: how can I verify that the server object created is actually representing a valid SQL Server instance?

I imagine something like: If $server.IsNotValid -eq "True" Then Throw Exception

share|improve this question

2 Answers 2

up vote 2 down vote accepted
$server.ConnectionContext.Connect()

will error if you are not able to connect to the server.

share|improve this answer
    
This is great. Interesting coincidence that I spent a good chunk of time yesterday reading your Powershell articles on SQLServerCentral. Thanks! –  8kb Sep 1 '10 at 16:26
    
Server class is kind of wierd in that it doesn't error out on non-existent servers. BTW you can also read the PowerShell module code at sqlpsx.codeplex.com. The code above comes from the Get-SqlServer function. –  Chad Miller Sep 1 '10 at 17:18

As far as I know you cannot test for a connection to SQL server until you try to retrieve a property (or explicitly make a connection with server connection) $conn = new-object Microsoft.SqlServer.Management.Common.ServerConnection

I can't test it right now but I believe that you will get an error if the connection call fails. If not you should if you try to retrieve any property.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.