Avatar of kuintencst
kuintencst

asked on 

How to write a vbs script to query and find all servers

I have a script that has a list of servers but some of those are not in action and gives invaild information and we also add new servers as well, what script is out there where it can find all servers. It can overwrite the text file if thats easier right know once it checks all ther servers it finds how much disk space, used, free and a precentage then it emails us the results every morning I use the following vbs to do this below:
on error resume next
 
Set iFSO = CreateObject("Scripting.FilesyStemObject")
 Set oFSO = CreateObject("Scripting.FilesyStemObject")
 
InputFile="C:\utilities\computerlist.txt"
 Outputfile="C:\utilities\Freespacelist_" + cstr(Month(now()))+"_"+cstr(day(now()))+".csv" 
 
 
 Set ofile = ofso.createTextFile(OutputFile, True)
 Set ifile = iFSO.OpenTextFile(inputfile) 
 
 Const GBCONVERSION= 1073741824 
 
 ofile.writeline "Computer,Drive,Disk Size,GBFreeSpace,%"
 Do until ifile.AtEndOfLine
 
     Computer = ifile.ReadLine
 
     Set objWMIService = GetObject("winmgmts://" & Computer) 
     Set colLogicalDisk = objWMIService.InstancesOf("Win32_LogicalDisk") 
     For Each objLogicalDisk In colLogicalDisk
 
         if objLogicalDisk.drivetype=3 Then
             ofile.writeline Computer & "," & objLogicalDisk.DeviceID &_
             "," &  Round(objLogicalDisk.size/GBCONVERSION) & "," &_
             Round(objLogicalDisk.freespace/GBCONVERSION) & "," &_
             Round(((objLogicalDisk.freespace/GBCONVERSION)/(objLogicalDisk.size/GBCONVERSION))*100) & "%"
 
 
       end If
set objWMISerivce = nothing
Set colLogicalDisk = nothing
    next
 Loop 
ofile.close
ifile.close

Open in new window

VB Script

Avatar of undefined
Last Comment
kuintencst
Avatar of Serge Fournier
Serge Fournier
Flag of Canada image

just tagging it to do it later
(i must do this for my network as well)

do all servers are in the same domain?
Avatar of sirbounty
sirbounty
Flag of United States of America image

Something like this?
'on error resume next
 
 Set oFSO = CreateObject("Scripting.FilesyStemObject")
 
InputFile="C:\utilities\computerlist.txt"
Outputfile="C:\utilities\Freespacelist_" & cstr(Month(now())) & "_" & cstr(day(now())) & ".csv" 
 
 Set ofile = oFSO.createTextFile(OutputFile, True)
 Set ifile = oFSO.OpenTextFile(inputfile) 
 
 Const GBCONVERSION= 1073741824 
 
 ofile.writeline "Computer,Drive,Disk Size,GBFreeSpace,%"
 Do until ifile.AtEndOfLine
      Computer = ifile.ReadLine
     If Ping(Computer) Then
     Set objWMIService = GetObject("winmgmts://" & Computer) 
     Set colLogicalDisk = objWMIService.InstancesOf("Win32_LogicalDisk") 
     For Each objLogicalDisk In colLogicalDisk
          if objLogicalDisk.drivetype=3 Then
             ofile.writeline Computer & "," & objLogicalDisk.DeviceID &_
             "," &  Round(objLogicalDisk.size/GBCONVERSION) & "," &_
             Round(objLogicalDisk.freespace/GBCONVERSION) & "," &_
             Round(((objLogicalDisk.freespace/GBCONVERSION)/(objLogicalDisk.size/GBCONVERSION))*100) & "%"
       end If
       set objWMISerivce = nothing
        Set colLogicalDisk = nothing
    End If
    next
 Loop 
ofile.close
ifile.close
 
Function Ping(strHost)
  Dim objPing, ret
  set objPing = GetObject("winmgmts:{impersonationLevel=impersonate}").ExecQuery ("SELECT * FROM Win32_PingStatus WHERE Address = '" & strHost & "'")
  For Each ret in objPing
    If IsNull(objRetStatus.StatusCode) or objRetStatus.StatusCode<>0 then
      Ping = False
    Else
       Ping = True
     End if
   Next
  Set objPing = Nothing
  Set ret = Nothing
End Function 
 
Sub SendMail()
  Dim objEmail :  Set objEmail = CreateObject("CDO.Message")
 
  With objEmail
       .Configuration.Fields.Item  ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
       .Configuration.Fields.Item  ("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtpServer"
       .Configuration.Fields.Item  ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
       .Configuration.Fields.Update
 
     .From = "Report@Company.com"
     .To = "You@Company.com"
     .Subject = "Notice"
     .Textbody = "Here's your report...."
     .AddAttachment Outputfile
     .Send
  End With
  Set objEmail = Nothing
End Sub

Open in new window

sirbounty:

what about new servers? ;)

here is my starting script that i will modify later:
(discover all computer in domain and scan for a process)

all i got to do is change the scan for process for chek if it's a server type, then add the code from the asker

but it is for a domain...

' cscript GetListofComputers.vbs //nologo > computers.txt
' This script outputs a list of all the computers in your domain.
' The only thing you need to modify is the value of yourDomain.
' Replace LDAP://DC=montereytechgroup,DC=com with the 
' LDAP name of your domain.
 
Set objFSO = wscript.CreateObject("Scripting.FileSystemObject")
thepath=WScript.ScriptFullName
p = instrRev(thepath,"\")
basedir  = left(thepath,p)
 
dim bad(50)
 
a = "zz_log_fini_TOUT_comp" & basename & ".txt"
 
Set objFil02 = objFso.OpenTextFile(basedir & a, 2, true)
If Err.number <> 0 Then
   Set objFil02 = objfso.OpenTextFile("c:\_stas\logs\" & a, 2, true)
end if
 
objFil02.WriteLine date & " " & time & " === log ldap start"
 
Set oRootDSE = GetObject("LDAP://RootDSE")
Set oDomain = GetObject("LDAP://" & oRootDSE.Get("DefaultNamingContext"))
'yourDomain="'LDAP://DC=domain,DC=company,DC=com'"
yourDomain="'" & cstr(oDomain.ADsPath) & "'"
 
'msgbox(yourdomain)
 
Const ADS_SCOPE_SUBTREE = 2
 
'=== Connect to Active Directory.
Set objConnection = CreateObject("ADODB.Connection")
Set objCommand = CreateObject("ADODB.Command")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"
 
'=== Create a query for all computers in the domain.
Set objCommand.ActiveConnection = objConnection
objCommand.CommandText = "Select cn from " & yourDomain & " where objectClass='computer'" 
objCommand.Properties("Page Size") = 1000
objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE 
'wscript.echo objCommand.CommandText
Set objRecordSet = objCommand.Execute
objRecordSet.MoveFirst
 
'=== Loop though all computers in the domain.
 
i2=0
i3=0
Do Until objRecordSet.EOF
 
   '=== Write each computer name out to the file.
 
   strcomputer = objRecordSet.Fields("cn").Value
   a = FastPing(strComputer)
 
   '=== start wmi on the computer we found
if a=1 then
   i3=i3+1
   on error resume next
   Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
      
   if err=0 then
      'objFil02.WriteLine date & " " & time & " " & i3 & " " & strcomputer & " scanning"
      '=== list all process of this pc
      '=== find certains program that are used to slow down internet connection
 
      bad(00)="emule.exe"
      bad(01)="kaza.exe"
      bad(02)="utorrent.exe"
      bad(03)="soulseek.exe"
      bad(04)="bittorrent.exe"
      bad(05)="winword.exe"
      bad(06)="bitcomet.exe"
      bad(07)="napster.exe"
      bad(08)="cuteftp.exe"
      bad(09)="mirc.exe"
      bad(10)="msnmsgr.exe"
      bad(11)="limewire.exe"
      bad(12)=""
      
      i=0
      do while bad(i)<>""
         'objFil02.WriteLine date & " " & time & " " & strcomputer & " scanning for: " & bad(i)
         strQuery = "Select * from Win32_Process Where Name = '" & bad(i) & "'"
      
         Set colProcesses = objWMIService.ExecQuery(strQuery)
         For Each objProcess In colProcesses
            If lCase(objProcess.Name) = bad(i) Then
               objFil02.WriteLine date & " " & time & " " & i3 & " " & strcomputer & "      " & bad(i) & " running"
            End If
         Next
         i=i+1
      loop
      'objFil02.WriteLine date & " " & time & " " & strcomputer & " " & a & " " & B
      'On Error Resume Next
      Set objWMIService = nothing
   else
      '=== error getting object
      err.clear
      objFil02.WriteLine date & " " & time & " " & strcomputer & " no answer"
   end if
end if
   objRecordSet.MoveNext
   i2=i2+1
Loop
 
objFil02.WriteLine date & " " & time & " fini tout"
 
'---------------------------------------
 
'My fast ping function
Function FastPing(strComputer)
   
   Set WshShell = WScript.CreateObject("WScript.Shell")
   return = WshShell.Run("ping "&strComputer&" -n 1 -w 500", 0, true)
   
   if return = 0 then 
      return = 1
   Else 
      return = 0
   End if
   fastping = return
End function
'---------------------------------------
 
function slowping(strComputer)
 
'=== IP address or hostname
strTarget = strcomputer
 
ON ERROR RESUME NEXT
 
Set colPings = objWMIService.ExecQuery ("Select * From Win32_PingStatus where Address = '" & strTarget & "'")
 
If Err = 0 Then
  Err.Clear
  For Each objPing in colPings
    If Err = 0 Then
      Err.Clear
      If objPing.StatusCode = 0 Then
        aa = aa & strTarget & " responded to ping."
        aa = aa & "Responding Address: " & objPing.ProtocolAddress
        aa = aa & "Responding Name: " & objPing.ProtocolAddressResolved
        aa = aa & "Bytes Sent: " & objPing.BufferSize
        aa = aa & "Time: " & objPing.ResponseTime & " ms"
        aa = aa & "TTL: " & objPing.ResponseTimeToLive & " seconds"
      Else
        aa = aa & strTarget & " did not respond to ping."
        aa = aa & "Status Code: " & objPing.StatusCode
      End If
    Else
      Err.Clear
      aa = aa & "Unable to call Win32_PingStatus on " & strComputer & "."      
    End If
  Next
Else
  Err.Clear
  aa = aa & "Unable to call Win32_PingStatus on " & strComputer & "."
End If
slowping = aa
 
end function
'--------------------------------------
 
function finip(strcomputer)
 
Set colNicConfigs = objWMIService.ExecQuery _
 ("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True")
 
'objFil02.WriteLine VbCrLf & "Computer Name: " & strComputer
'objFil02.WriteLine " IP Addresses & Subnet Masks"
 
For Each objNicConfig In colNicConfigs
  'WScript.Echo VbCrLf & "  Network Adapter " & objNicConfig.Index
  'WScript.Echo "    " & objNicConfig.Description & VbCrLf 
  'objFil02.WriteLine " IP Address(es): "
  For Each strIPAddress In objNicConfig.IPAddress
    objFil02.WriteLine " ip address: " & strIPAddress
  Next
  'WScript.Echo "    Subnet Mask(s):"
  For Each strIPSubnet In objNicConfig.IPSubnet
  '  WScript.Echo "        " & strIPSubnet
  Next
Next
 
end function
'-------------------------------------------

Open in new window

Avatar of kuintencst
kuintencst

ASKER

I want to query and find all servers, I have the email field in the vbs done
Avatar of kuintencst
kuintencst

ASKER

I will try this
so are the server all in the same domain?
(for a ldap scan)
Avatar of kuintencst
kuintencst

ASKER

hmm i think, we have 3 different ones but im hoping that they are in the same domain
Avatar of RobSampson
RobSampson
Flag of Australia image

Hi guys...what if we start with the code from here:

How Can I Get a List of All My Windows Server 2003 Computers?
http://www.microsoft.com/technet/scriptcenter/resources/qanda/feb05/hey0202.mspx

and then just ping those machines, and if they respond, get the details?

Regards,

Rob.
'on error resume next
 
Set iFSO = CreateObject("Scripting.FilesyStemObject")
 Set oFSO = CreateObject("Scripting.FilesyStemObject")
 
 Outputfile="C:\utilities\Freespacelist_" + cstr(Month(now()))+"_"+cstr(day(now()))+".csv" 
 
 
 Set ifile = iFSO.OpenTextFile(inputfile) 
 
 Const GBCONVERSION= 1073741824 
 
 ofile.writeline "Computer,Drive,Disk Size,GBFreeSpace,%"
Const ADS_SCOPE_SUBTREE = 2
 
Set objConnection = CreateObject("ADODB.Connection")
Set objCommand = CreateObject("ADODB.Command")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"
 
Set objCommand.ActiveConnection = objConnection
Set objRootDSE = GetObject("LDAP://RootDSE")
strDomain = objRootDSE.Get("defaultNamingContext")
objCommand.CommandText = _
    "SELECT Name FROM 'LDAP://" & strDomain & "' WHERE objectClass='computer' " & _
        "and operatingSystemVersion = '5.2 (3790)'"  
objCommand.Properties("Page Size") = 1000
objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE 
Set objRecordSet = objCommand.Execute
objRecordSet.MoveFirst
 
Do Until objRecordSet.EOF
	Computer = objRecordSet.Fields("Name").Value
 
	Set objWMIService = GetObject("winmgmts://" & Computer) 
	Set colLogicalDisk = objWMIService.InstancesOf("Win32_LogicalDisk") 
	For Each objLogicalDisk In colLogicalDisk
		If objLogicalDisk.drivetype=3 Then
			ofile.writeline Computer & "," & objLogicalDisk.DeviceID &_
				"," &  Round(objLogicalDisk.size/GBCONVERSION) & "," &_
				Round(objLogicalDisk.freespace/GBCONVERSION) & "," &_
				Round(((objLogicalDisk.freespace/GBCONVERSION)/(objLogicalDisk.size/GBCONVERSION))*100) & "%"
		End If
		Set objWMISerivce = Nothing
		Set colLogicalDisk = Nothing
    Next
	objRecordSet.MoveNext
Loop 
ofile.close
MsgBox "Done"

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of RobSampson
RobSampson
Flag of Australia image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
aw, look like this time i was too slow ;)

i was working on it, but with my super web interface (iexplorer with buttons to execute my numerous vbscripts hehe)

Avatar of RobSampson
RobSampson
Flag of Australia image

Thanks for the grade.

Regards,

Rob.
Avatar of kuintencst
kuintencst

ASKER


on error resume next
 
Set iFSO = CreateObject("Scripting.FilesyStemObject")
 Set oFSO = CreateObject("Scripting.FilesyStemObject")
 
 Outputfile="C:\Documents and Settings\krucker\Desktop\Time Sheets\Freespacelist_" + cstr(Month(now()))+"_"+cstr(day(now()))+".csv" 
 
 Set ofile = ofso.createTextFile(OutputFile, True)
 Set ifile = iFSO.OpenTextFile(inputfile) 
 
 Const GBCONVERSION= 1073741824 
 
 ofile.writeline "Computer,Drive,Disk Size,GBFreeSpace,%"
Const ADS_SCOPE_SUBTREE = 2
 
Set objConnection = CreateObject("ADODB.Connection")
Set objCommand = CreateObject("ADODB.Command")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"
 
Set objCommand.ActiveConnection = objConnection
Set objRootDSE = GetObject("LDAP://RootDSE")
strDomain = objRootDSE.Get("defaultNamingContext")
objCommand.CommandText = _
    "SELECT Name FROM 'LDAP://" & strDomain & "' WHERE objectClass='computer' " & _
        "and operatingSystemVersion = '5.2 (3790)'"  
objCommand.Properties("Page Size") = 1000
objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE 
Set objRecordSet = objCommand.Execute
objRecordSet.MoveFirst
 
Do Until objRecordSet.EOF
	Computer = objRecordSet.Fields("Name").Value
 
	If Ping(Computer) = True Then
		Set objWMIService = GetObject("winmgmts://" & Computer) 
		Set colLogicalDisk = objWMIService.InstancesOf("Win32_LogicalDisk") 
		For Each objLogicalDisk In colLogicalDisk
			If objLogicalDisk.drivetype=3 Then
				ofile.writeline Computer & "," & objLogicalDisk.DeviceID &_
					"," &  Round(objLogicalDisk.size/GBCONVERSION) & "," &_
					Round(objLogicalDisk.freespace/GBCONVERSION) & "," &_
					Round(((objLogicalDisk.freespace/GBCONVERSION)/(objLogicalDisk.size/GBCONVERSION))*100) & "%"
			End If
			Set objWMISerivce = Nothing
			Set colLogicalDisk = Nothing
	
	
	End If
	objRecordSet.MoveNext
Loop 
ofile.close
MsgBox "Done"
 
Function Ping(strComputer)
	Dim objShell, boolCode
	Set objShell = CreateObject("WScript.Shell")
	boolCode = objShell.Run("Ping -n 1 -w 300 " & strComputer, 0, True)
	If boolCode = 0 Then
		Ping = True
	Else
		Ping = False
	End If
 
set objWMISerivce = nothing
Set colLogicalDisk = nothing
    next
 Loop 
ofile.close
ifile.close
 
strFrom = "kuinten.rucker@sonicdrivein.com"
strTo = "networknotificationemailonly@sonicdrivein.com,kuinten.rucker@sonicdrivein.com"
strSub = "Super Sonic Script Output"
strBody = "Sonic Server DiskSpace"
strSMTP = "exchange2.sonicdrivein.com"
 
' ------ END CONFIGURATION ---------
set objEmail = CreateObject("CDO.Message")
objEmail.AddAttachment "C:\utilities\Freespacelist_" + cstr(Month(now()))+"_"+cstr(day(now()))+".csv"
objEmail.From = strFrom
objEmail.To = strTo
objEmail.Subject = strSub
objEmail.Textbody = strBody
objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = strSMTP
objEmail.Configuration.Fields.Update
objEmail.Send
'WScript.Echo "Sonic Server Disk Space Email sent"

Open in new window

VB Script
VB Script

VBScript (Visual Basic Scripting Edition) is an interpreted scripting language developed by Microsoft that is modeled on Visual Basic, but with some important differences. VBScript is commonly used for automating administrative and other tasks in Windows operating systems (by means of the Windows Script Host) and for server-side scripting in ASP web applications. It is also used for client-side scripting in Internet Explorer, specifically in intranet web applications.

39K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts
Ask the experts
Read over 600 more reviews

TRUSTED BY

IBM logoIntel logoMicrosoft logoUbisoft logoSAP logo
Qualcomm logoCitrix Systems logoWorkday logoErnst & Young logo
High performer badgeUsers love us badge
LinkedIn logoFacebook logoX logoInstagram logoTikTok logoYouTube logo