Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

vbscript extract sql instances and version

Posted on 2008-06-23
11
Medium Priority
?
2,772 Views
Last Modified: 2009-07-29
Hello using vbscript and WMI or otherwise I am looking to list all SQL instances and their SQL version including build level (e.g.  2005.90.3042). Anyone got suggestion to achieving this?
Thanks
0
Comment
Question by:nmxsupport
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
11 Comments
 
LVL 67

Expert Comment

by:sirbounty
ID: 21845172
Here's a piece I used a while back - I haven't updated it for sql 2005, but you can get a good idea anyway...
Dim objShell : Set objShell = CreateObject("Wscript.Shell")
strCmd = "oSql -E -Q " & chr(34) & "SELECT @@Version" & chr(34)
Dim objExec : Set objExec = objShell.Exec(strCmd)
strOut = Split(objExec.StdOut.ReadAll, vbNewLine)
For Each item in strOut
  If Instr(oItem, "SQL") > 0 Then
    strBuild=Trim(Mid(item,"-")+1,InstrRev(Item,"(")-(Instr(Item,"-")+1)))
  End If
Next
 
Select Case strBuild
  Case "8.00.194"
    strVer="SQL Server 2000"
    strSP=""
  Case "8.00.384"
    strVer="SQL Server 2000"
    strSP="1"
  Case "8.00.534"
    strVer="SQL Server 2000"
    strSP="2"
  Case "8.00.760"
    strVer="SQL Server 2000"
    strSP="3"
  Case "8.00.818"
    strVer="SQL Server 2000"
    strSP="3a"
End Select

Open in new window

0
 
LVL 65

Expert Comment

by:RobSampson
ID: 21850487
Hi, I've never done much scripting with SQL Server, but here's one I used to get instances.
http://www.experts-exchange.com/Microsoft/Development/MS-SQL-Server/Q_22925099.html

Regards,

Rob.
0
 

Author Comment

by:nmxsupport
ID: 21853710
Hmmm that works well to give all databases on the default instance - but looking to list all the instances on a named server and the version SQL of each one.
0
Moving data to the cloud? Find out if you’re ready

Before moving to the cloud, it is important to carefully define your db needs, plan for the migration & understand prod. environment. This wp explains how to define what you need from a cloud provider, plan for the migration & what putting a cloud solution into practice entails.

 
LVL 65

Expert Comment

by:RobSampson
ID: 21861783
How does this go?

Rob.
arrServers = Array(_
      "SQLServer1", _
      "SQLServer2" _
      )
 
strOutputFile = "Servers_DBs.txt"
 
Set objServer = CreateObject("SQLDMO.SQLServer2")
'Set Authentication for Server
' Login with current Windows account
objServer.LoginSecure = True
 
strDBs = ""
For Each strServerName In arrServers
      objServer.Connect strServerName
      If strDBs = "" Then
            strDBs = "Server: " & strServerName & VbCrLf & _
            	"Major Version: " & objServer.Application.VersionMajor & VbCrLf & _
            	"Minor Version: " & objserver.Application.VersionMinor & VbCrLf & "========================"
      Else
            strDBs = strDBs & VbCrLf & VbCrLf & "Server: " & strServerName & VbCrLf & _
            	"Major Version: " & objServer.Application.VersionMajor & VbCrLf & _
            	"Minor Version: " & objserver.Application.VersionMinor & VbCrLf & "========================"
      End If
      MsgBox strDBs
      For Each objDatabase In objServer.Databases
            strDBs = strDBs & vbCrLf & objDatabase.Name
      Next
      objServer.Disconnect
Next
 
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objOutputFile = objFSO.CreateTextFile(strOutputFile, True)
objOutputFile.Write strDBs
objOutputFile.Close
Set objOutputFile = Nothing
Set objFSO = Nothing
 
MsgBox "Done. Please see " & strOutputFile

Open in new window

0
 

Author Comment

by:nmxsupport
ID: 21863663
Hi Rob, this works to list the sql version of the default instance for a given array of servers. However for each server there can be many other instances - each running their own version of SQL - it was this part I'm trying to extract.
0
 
LVL 65

Accepted Solution

by:
RobSampson earned 2000 total points
ID: 21863879
Hi, this probably does the job a bit better:
http://blog.netnerds.net/2007/01/vbscript-enumerating-all-sql-servers-on-a-domain/

Regards,

Rob.
0
 
LVL 65

Expert Comment

by:RobSampson
ID: 21871547
So from that link I posted, what does this code give you?

If you browse through the keys and values in
HKLM\Software\Microsoft\Microsoft SQL Server
on one of your SQL Servers, does that tell you what their versions are? If so, we could pull those out too.

Regards,

Rob.
Set objAdRootDSE = GetObject("LDAP://RootDSE")
Set objWMIService = GetObject("winmgmts:\\" & "." & "\root\cimv2")
Set objRS = CreateObject("adodb.recordset")
Const HKEY_LOCAL_MACHINE = &H80000002
 
varConfigNC = objAdRootDSE.Get("defaultNamingContext")
strConnstring = "Provider=ADsDSOObject"
 
arrServers = Array(_
	"SQLSERVER1", _
	"SQLSERVER2" _
	)
	
For Each strServer In arrServers
  strWQL = "SELECT * FROM 'LDAP://" & varConfigNC & "' WHERE objectCategory='Computer' and Name='" & strServer & "'"
  objRS.Open strWQL, strConnstring
      Do until objRS.eof
         Set objServer = GetObject(objRS.Fields.Item(0))
          strServerName = objServer.CN
 
          Set colItems = objWMIService.ExecQuery("Select * from Win32_PingStatus Where Address = '" & objServer.DNSHostName & "'")
          For Each objItem in colItems
              If objItem.StatusCode = 0 Then 'The Computer is Pingable
                    Set objRegistry = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strServerName & "\root\default:StdRegProv")
                      strKeyPath = "SOFTWARE\Microsoft\Microsoft SQL Server"
                      strValueName = "InstalledInstances"
                      objRegistry.GetMultiStringValue HKEY_LOCAL_MACHINE,strKeyPath, strValueName,arrValues
                        If IsNull(arrValues) = 0 Then 'It's a SQL Server! Enumerate it's instances
                          strMsg = strServerName & " is running the following SQL Instance(s): "
                          For Each strValue In arrValues
                              If strValue = "MSSQLSERVER" Then strValue = "Default Instance"
                                strMsg = strMsg & vbCrLf & strValue
                          Next
                          MsgBox strMsg
                        End If
                     Set objRegistry = Nothing
              End If
          Set objServer = Nothing
      Next
    objRS.movenext
    Loop
  objRS.close
Next
 
Set objWMIService = Nothing
Set objRS = Nothing
Set objAdRootDSE = Nothing

Open in new window

0
 
LVL 65

Expert Comment

by:RobSampson
ID: 21871564
Or, as SirBounty provided in his first post (did you try that?), perhaps the command line tools can do this better...
http://www.mssqltips.com/tip.asp?tip=1113

Rob.
0
 

Author Comment

by:nmxsupport
ID: 21872790
Rob, thanks for the links - they have provided me with a way to move forward. I've used the various sources to put together something which works for me.

Kind Regards.
sub chkSQL(strserver) '1.9
ON ERROR RESUME NEXT
  Set objRegistry = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & server & "\root\default:StdRegProv")
  strKeyPath = "SOFTWARE\Microsoft\Microsoft SQL Server"
  strValueName = "InstalledInstances"
  objRegistry.GetMultiStringValue HKEY_LOCAL_MACHINE,strKeyPath, strValueName,arrValues
	If not IsNull(arrValues) Then
		st = server
		For Each strValue In arrValues
			if strvalue = "MSSQLSERVER" then
				strInstance = server
			else
				strInstance = server & "\" & strvalue
			end if
			Set cxn = Wscript.CreateObject("ADODB.Connection")
			strConn = "Driver={SQL Server};Server=" & strInstance & ";Database=master"
 
			cxn.ConnectionString = strConn
			cxn.Open
			Set rs=cxn.Execute("SELECT @@version") 
			if not rs.eof then
        arr_1 = split(rs(0).value,"-")
				arr_2 = split(arr_1(1)," ")
				res.writeline("!!sql_instance==" & strInstance & "==" & arr_2(1))
			end if
		next
	end if
end sub

Open in new window

0
 
LVL 65

Expert Comment

by:RobSampson
ID: 21879796
Hi, that's great. Thanks for the grade, and thanks for posting your working code.

Regards,

Rob.
0
 

Expert Comment

by:Carlos_Felipe
ID: 22074729
A simplest way to get the instances:
str = "localhost"
Set objSQLDMOApp = CreateObject("SQLDMO.SQLServer2")
set objInstances = objSQLDMOApp.ListInstalledInstances(str)
For Count=1 To objInstances.Count
	WScript.Echo objInstances.Item(count)
Next

Open in new window

0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Ever needed a SQL 2008 Database replicated/mirrored/log shipped on another server but you can't take the downtime inflicted by initial snapshot or disconnect while T-logs are restored or mirror applied? You can use SQL Server Initialize from Backup…
With User Account Control (UAC) enabled in Windows 7, one needs to open an elevated Command Prompt in order to run scripts under administrative privileges. Although the elevated Command Prompt accomplishes the task, the question How to run as script…
Using examples as well as descriptions, and references to Books Online, show the documentation available for date manipulation functions and by using a select few of these functions, show how date based data can be manipulated with these functions.
This video shows how to set up a shell script to accept a positional parameter when called, pass that to a SQL script, accept the output from the statement back and then manipulate it in the Shell.

670 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question