Help needed with VB Script and producing an Excel Worksheet - excel

I am trying to create a VB Script which will produce an Excel based report on the disk space for the servers within my environment. I have 3 hurdles left which I can't get over.
How can I left align all of the columns/cells within the worksheet? Line 25 is where I have tried to do this however it throws the error, "Unable to set the HorizontalAlignment property of the Range class".
Some servers have more than 1 drive (eg C, D, E). When the script produces the report, it will only show the last drive (eg E). How can I make it show every drive for each server?
When I run the script, I would like it to append the report with the current day's disk usage. At the moment, it will replace the existing cells with the current day's disk usage.
The code for my script is as follows:
On Error Resume Next
Const ForReading = 1
Const HARD_DISK = 3
x = 1
dtmDate = Date
strDay = Day(Date)
strMonth = Month(Date)
strYear = Right(Year(Date), 2)
strFileName = "C:\Users\cvandal\Desktop\Scripts\Server_Disk_Space_Report.xlsx"
Set objFSO = CreateObject("Scripting.FileSystemObject")
If objFSO.FileExists("C:\Users\cvandal\Desktop\Scripts\Server_Disk_Space_Report.xlsx") Then
Set serverList = objFSO.OpenTextFile("servers.txt", ForReading)
Set objExcel = CreateObject("Excel.Application")
objExcel.Workbooks.Open "C:\Users\cvandal\Desktop\Scripts\Server_Disk_Space_Report.xlsx"
objExcel.Visible = True
objExcel.Columns("A:ZZ").ColumnWidth = 25
objExcel.Columns("A:ZZ").HorizontalAlignment = xlHAlignLeft
objExcel.Cells(2, 1).Value = "Server Disk Space Report"
objExcel.Cells(4, 1).Value = dtmDate
objExcel.Cells(5, 1).Value = "Drives:"
objExcel.Cells(6, 1).Value = "Total Capacity (in GB):"
objExcel.Cells(7, 1).Value = "Used Capacity (in GB):"
objExcel.Cells(8, 1).Value = "Free Space (in GB):"
objExcel.Cells(9, 1).Value = "Free Space (in %):"
Do Until serverList.AtEndOfStream
x = x + 1
strComputer = serverList.ReadLine
Set objWMIService = GetObject("winmgmts:{impersonationlevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colDisks = objWMIService.ExecQuery("SELECT * FROM Win32_LogicalDisk WHERE DriveType = " & HARD_DISK & "")
If Err.Number <> 0 Then
'WScript.Echo "Error: " & Err.Number
'WScript.Echo "Error (Hex): " & Hex(Err.Number)
'WScript.Echo "Source: " & Err.Source
'WScript.Echo "Description: " & Err.Description
objExcel.Cells(4, x).Value = strComputer & " - " & Err.Description
objExcel.Cells(4, x).Columns.AutoFit
Err.Clear
Else
For Each objDisk in colDisks
drives = "Error"
totalCapacity = 0
freeSpace1 = 0
usedCapacity = 0
freeSpace2 = 0
drives = objDisk.DeviceID
totalCapacity = Round((objDisk.Size / 1073741824), 2)
freeSpace1 = Round((objDisk.FreeSpace / 1073741824), 2)
usedCapacity = Round((totalCapacity - freeSpace1), 2)
freeSpace2 = Round((freeSpace1 / totalCapacity)*100, 0)
If freeSpace2 > 20 Then
objExcel.Cells(4, x).Value = strComputer
objExcel.Cells(5, x).Value = drives
objExcel.Cells(6, x).Value = totalCapacity & " GB"
objExcel.Cells(7, x).Value = usedCapacity & " GB"
objExcel.Cells(8, x).Value = freeSpace1 & " GB"
objExcel.Cells(9, x).Value = freeSpace2 & "%"
objExcel.Cells(9, x).Interior.Color = RGB(198,239,206)
ElseIf freeSpace2 < 10 Then
objExcel.Cells(4, x).Value = strComputer
objExcel.Cells(5, x).Value = drives
objExcel.Cells(6, x).Value = totalCapacity & " GB"
objExcel.Cells(7, x).Value = usedCapacity & " GB"
objExcel.Cells(8, x).Value = freeSpace1 & " GB"
objExcel.Cells(9, x).Value = freeSpace2 & "%"
objExcel.Cells(9, x).Interior.Color = RGB(255,199,206)
Else
objExcel.Cells(4, x).Value = strComputer
objExcel.Cells(5, x).Value = drives
objExcel.Cells(6, x).Value = totalCapacity & " GB"
objExcel.Cells(7, x).Value = usedCapacity & " GB"
objExcel.Cells(8, x).Value = freeSpace1 & " GB"
objExcel.Cells(9, x).Value = freeSpace2 & "%"
objExcel.Cells(9, x).Interior.Color = RGB(255,235,156)
End If
Next
End If
Loop
Else
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = False
Set objWorkbook = objExcel.Workbooks.Add()
objWorkbook.SaveAs(strFileName)
objExcel.Quit
WScript.Echo "Server_Disk_Space_Report.xlsx has been created. Please re-run the script."
End If

It doesn't look like you've defined a constant for the value of xlHAlignLeft.
You should increment the counter x inside of your disk loop:
For Each objDisk in colDisks
x = x + 1 ' <-- add this line
You'll probably have to play with where exactly in the code you increment the counter, depending on how you want the output to look. I think the place I put it in my example would result in a blank line between each machine.
The trick here is to initialize x to the first available row, instead of always defaulting to 1. The following code searches the first column ('A') for the last non-empty row. (reference)
Const xlUp = -4162
x = objExcel.Cells(Rows.Count, 1).End(xlUp).Row

Did you know that you can put the markup for HTML tables into a .xls file and open it with Excel? It even works for Excel 2000! Try it, and you'll be so much happier that you don't have to create the "Excel.Application" COM object!

Related

Hyperlinks.add changes hyperlink unwanted

I have used hyperlinks.add several times now and never had any problems with it.
Now I added a line of code: SourceBook.Sheets(ESN & "_SV" & SV).Hyperlinks.Add Anchor:=Range("A" & i), _
Address:=ToPath & NewName to my base code (which you can find under here). This should add a link to the newly created document.
The problem is that excel always says it cannot open the file. The link I enter via code is right, as I copied it with debug.print and it opened the file without a problem.
It came to my attention that the hyperlink I added was modified by excel when I hold my mouse over the hyperlink. I wonder how this is possible.
A second problem I encounterd is that when I enter the hyperlink manually and navigate manually to the file to make sure it takes the right file, excel still modifies my link and says "cannot open specified file".
Anyone an idea what might go wrong here? Thanks!
Code:
`Application.ScreenUpdating = False
Dim i, j, FSO As Object, SV, ESN, PartName, ToPath, FromPath, NewName, MsgBoxAnswer, TargetBook As Workbook, SourceBook As Workbook
Dim OS, PN, SN, ProjectNumber, Customer, StartDate, EndDate, LastRowCMM
ESN = ActiveWorkbook.ActiveSheet.Range("G2").Value
SV = ActiveWorkbook.ActiveSheet.Range("K2").Value
ProjectNumber = ActiveWorkbook.ActiveSheet.Range("A3").Value
Customer = ActiveWorkbook.ActiveSheet.Range("G3").Value
Set FSO = CreateObject("scripting.filesystemobject")
PGB.Min = 0
PGB.Value = 0
PGB.Max = 22
'Create main folder
If SV <> 1 Then
SV = "(SV " & SV & ")"
ToPath = "U:\tmo\vanmolle\fiches constat\Fiches constats #" & ESN & " " & SV
Else
ToPath = "U:\tmo\vanmolle\fiches constat\Fiches constats #" & ESN
End If
If FSO.folderexists(ToPath) = True Then
MsgBoxAnswer = MsgBox("Folder already created.", vbExclamation, "Folder exists.")
Exit Sub
End If
FSO.createfolder (ToPath)
'Create all Excel files & fill them in
For i = 6 To 27
FromPath = "U:\tmo\VANMOLLE\Fiches constat\Template fiches constat LEAP.xlsm"
If SV <> 1 Then
ToPath = "U:\tmo\vanmolle\fiches constat\Fiches constats #" & ESN & " " & SV & "\"
Else
ToPath = "U:\tmo\vanmolle\fiches constat\Fiches constats #" & ESN & "\"
End If
FSO.copyfile Source:=FromPath, Destination:=ToPath
NewName = "#" & ESN & "_" & ActiveWorkbook.ActiveSheet.Range("A" & i) & ".xlsm"
If SV <> 1 Then
FromPath = "U:\tmo\vanmolle\fiches constat\Fiches constats #" & ESN & " " & SV & "\Template fiches constat LEAP.xlsm"
Else
FromPath = "U:\tmo\vanmolle\fiches constat\Fiches constats #" & ESN & "\Template fiches constat LEAP.xlsm"
End If
Name FromPath As ToPath & NewName
Set SourceBook = ThisWorkbook
Set TargetBook = Workbooks.Open(ToPath & NewName)
TargetBook.Sheets("Sheet1").Activate
PartName = SourceBook.ActiveSheet.Range("A" & i).Value
OS = SourceBook.ActiveSheet.Range("D" & i).Value
PN = SourceBook.ActiveSheet.Range("B" & i).Value
SN = SourceBook.ActiveSheet.Range("C" & i).Value
If SN = "" Then SN = "N/A"
StartDate = SourceBook.ActiveSheet.Range("G" & i).Value
EndDate = SourceBook.ActiveSheet.Range("H" & i).Value
'check for right CMM
'LastRowCMM = TargetBook.Sheets("Révision CMM").Range("B6").End(xlDown).Row
'For j = 1 To LastRowCMM
'If PartName = TargetBook.Sheets("Révision CMM").Range("A" & j).Value Then ActiveWorkbook.ActiveSheet.Range("A23").Value = ActiveWorkbook.Sheets("Révision CMM").Range("B" & j).Value
'Next j
TargetBook.ActiveSheet.Range("B9").Value = PartName
TargetBook.ActiveSheet.Range("B10").Value = OS
TargetBook.ActiveSheet.Range("B11").Value = "# " & ESN
TargetBook.ActiveSheet.Range("B12").Value = PN
TargetBook.ActiveSheet.Range("B13").Value = SN
TargetBook.ActiveSheet.Range("E9").Value = StartDate
TargetBook.ActiveSheet.Range("E10").Value = EndDate
TargetBook.ActiveSheet.Range("B14").Value = ProjectNumber
TargetBook.ActiveSheet.Range("B15").Value = Customer
TargetBook.ActiveSheet.PageSetup.PrintArea = "$A$1:$E$39"
TargetBook.Close True
'Add hyperlink
SourceBook.Sheets(ESN & "_SV" & SV).Hyperlinks.Add Anchor:=Range("A" & i), _
Address:=ToPath & NewName
Application.Wait (Now + TimeValue("00:00:01"))
Progress.PGB.Value = i - 5
Progress.Lbl.Caption = "File " & i - 5 & " of 22 copied."
Next i
Application.ScreenUpdating = True`
First thing first - declare each variable explicitly. E.g.:
Dim i as Long, j as Long, FSO As Object, SV as String, ESN as String and etc.
The way in your code - Dim i, j, SV, ESN, PartName, ToPath they are declared as variant.
Second thing second - try something really very small to debug further. E.g. write this small piece:
Sub TestMe()
With Worksheets(1)
.Hyperlinks.Add anchor:=.Range("A1"), Address:="C:\Users\UserName\Desktop\test.docx"
End With
End Sub
and check whether it works. If it doesn't, debug further, check whether cells are locked or anything similar.

VBScript Write to Excel not writing

What I'm trying to accomplish is searching multiple computers for event code 41 (unexpected shutdown) in the windows system log, then write that into an excel file for each instance for each computer.
I receive no errors, but nothing is ever written into the excel file. I set up an echo to make sure it was reaching the correct part of the loop (it does!) and I set a literal entry to see if there was an error with the variables (it didn't write). At this point, I'm at a loss.
' https://technet.microsoft.com/library/ee176684.aspx
' http://blogs.technet.com/b/heyscriptingguy/archive/2009/04/06/how-can-i-check-my-event-logs.aspx
' http://stackoverflow.com/questions/21738159/extracting-error-logs-from-windows-event-viewer
Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("H:\Chris Created Stuffs\Windows Stuffs\check_error_41.xlsx")
objExcel.Visible = False
i = 1
x = 0
'On error resume next
'This is the code that will read the computer names off of the
'appropriate spreadhseet
Do Until objExcel.Cells(i, 1).Value = ""
ReDim Preserve strPC(x)
strPC(x) = objExcel.Cells(i, 1).Value
i = i + 1
x = x + 1
Loop
'And this is the code that will write the success or failure
'data in the Excel spreadsheet
Set objSheet1 = objWorkbook.sheets("Missed")
Set objSheet2 = objWorkbook.sheets("Sheet1")
'Set objSheet1 = objExcel.ActiveWorkbook.Worksheets(1)
'Set objSheet2 = objExcel.ActiveWorkbook.Worksheets(2)
f = 1
m = 1
'Set obj = CreateObject("Scripting.FileSystemObject")
For Each strPC In strPC
Set objWMIService = GetObject("winmgmts:\\" & strPC & "\root\cimv2")
Set colItems = objWMIService.ExecQuery("Select * from Win32_NTLogEvent WHERE LogFile='System'")
If Err.Number <> 0 Then
'objSheet1.Add
objSheet1.Cells(f, 1).Value = strPC
objSheet1.Cells(f, 2).Value = err.number
f = f + 1
Err.clear
Else
For Each objEvent in colItems
If objEvent.EventCode = 41 Then
'writeLog "Event Code: " & objEvent.EventCode
'writeLog "Event Identifier: " & objEvent.EventIdentifier
'writeLog "Logfile: " & objEvent.Logfile
'writeLog "Message: " & objEvent.Message
'writeLog "Record Number: " & objEvent.RecordNumber
'writeLog "Source Name: " & objEvent.SourceName
'writeLog "Time Generated: " & objEvent.TimeGenerated
'writeLog "Time Written: " & objEvent.TimeWritten
'objSheet2.Add
objSheet2.Cells(m,1).Value = strPC
objSheet2.Cells(m,2).Value = objEvent.EventCode
objSheet2.Cells(m,3).Value = objEvent.EventIdentifier
objSheet2.Cells(m,4).Value = objEvent.Logfile
objSheet2.Cells(m,5).Value = objEvent.Message
objSheet2.Cells(m,6).Value = objEvent.RecordNumber
objSheet2.Cells(m,7).Value = objEvent.SourceName
objSheet2.Cells(m,8).Value = objEvent.TimeGenerated
objSheet2.Cells(m,9).Value = objEvent.TimeWritten
objSheet2.Cells(m,10).Value = "Listen!"
m = m + 1
wscript.echo "We Got One!!!!"
Else
m = m + 1
End If
Next
Err.clear
End If
Next
objExcel.ActiveWorkbook.Save
objExcel.Quit
wscript.echo "Done"
I think your primary problem was ignoring the Workbook Object and Worksheet Object. In this code:
Do Until objExcel.Cells(i, 1).Value = ""
ReDim Preserve strPC(x)
strPC(x) = objExcel.Cells(i, 1).Value
i = i + 1
x = x + 1
Loop
Nothing is actually being pulled from the worksheet. I've had to guess a little as to the actual origin but the syntax is correct; you may have to make specific adjustments to your own worksheet layout.
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True 'False
Set objWorkbook = objExcel.Workbooks.Open("H:\Chris Created Stuffs\Windows Stuffs\check_error_41.xlsx")
i = 1
x = 0
'On error resume next
'This is the code that will read the computer names off of the appropriate spreadhseet
Do Until objWorkbook.Worksheets(1).Cells(i, 1).Value = ""
ReDim Preserve strPCs(x)
strPCs(x) = objWorkbook.Worksheets(1).Cells(i, 1).Value
'msgbox objWorkbook.Worksheets(1).Cells(i, 1).Value
i = i + 1
x = x + 1
Loop
'And this is the code that will write the success or failure data in the Excel spreadsheet
Set objSheet1 = objWorkbook.Worksheets("Missed")
Set objSheet2 = objWorkbook.Worksheets("Sheet1")
f = 1
m = 1
For Each strPC In strPCs
Set objWMIService = GetObject("winmgmts:\\" & strPC & "\root\cimv2")
Set colItems = objWMIService.ExecQuery("Select * from Win32_NTLogEvent WHERE LogFile='System'")
If Err.Number <> 0 Then
'objSheet1.Add
objSheet1.Cells(f, 1).Value = strPC
objSheet1.Cells(f, 2).Value = err.number
f = f + 1
Err.clear
Else
For Each objEvent in colItems
If objEvent.EventCode = 41 Then
'writeLog "Event Code: " & objEvent.EventCode
'writeLog "Event Identifier: " & objEvent.EventIdentifier
'writeLog "Logfile: " & objEvent.Logfile
'writeLog "Message: " & objEvent.Message
'writeLog "Record Number: " & objEvent.RecordNumber
'writeLog "Source Name: " & objEvent.SourceName
'writeLog "Time Generated: " & objEvent.TimeGenerated
'writeLog "Time Written: " & objEvent.TimeWritten
'objSheet2.Add
objSheet2.Cells(m, 1).Value = strPC
objSheet2.Cells(m, 2).Value = objEvent.EventCode
objSheet2.Cells(m, 3).Value = objEvent.EventIdentifier
objSheet2.Cells(m, 4).Value = objEvent.Logfile
objSheet2.Cells(m, 5).Value = objEvent.Message
objSheet2.Cells(m, 6).Value = objEvent.RecordNumber
objSheet2.Cells(m, 7).Value = objEvent.SourceName
objSheet2.Cells(m, 8).Value = objEvent.TimeGenerated
objSheet2.Cells(m, 9).Value = objEvent.TimeWritten
objSheet2.Cells(m, 10).Value = "Listen!"
m = m + 1
'wscript.echo "We Got One!!!!"
'do not add to m on no-write; it only creates blank rows
End If
Next
Err.clear
End If
Next
'objWorkbook.Close True
'objExcel.Quit
wscript.echo "Done"
I've commented out the code lines to make the Excel application object hidden as to save asn close it in order that you can observe the process. Uncomment them once you are happy with the process.

Script that scans IP range and gets user information to Excel sheet. Recycles information

I need help with a VBS script that produces an Excel sheet with specific user information.
It works... Sort of. The problem is that it seems to recycle information producing inaccurate results. Anybody know how I would go about making the script leave areas in the Excel document blank when no information is available? I know it's possible, just need a nudge in the right direction.
Thank you!
On Error Resume Next
Dim FSO
Dim objStream
Const TriStateFalse = 0
Const FILE_NAME = "Users.csv"
Set FSO = CreateObject("Scripting.FileSystemObject")
Set objStream = FSO.CreateTextFile(FILE_NAME, _
True, TristateFalse)
strSubnetPrefix = "192.168.1."
intBeginSubnet = 1
intEndSubnet = 254
For i = intBeginSubnet To intEndSubnet
strComputer = strSubnetPrefix & i
'strcomputer = inputbox("Enter Computer Name or IP")
if strcomputer = "" then
wscript.quit
else
Set objPing = GetObject("winmgmts:{impersonationLevel=impersonate}").ExecQuery _
("select * from Win32_PingStatus where address = '" & strcomputer & "'")
For Each objStatus in objPing
If IsNull(objStatus.StatusCode) or objStatus.StatusCode<>0 Then
'request timed out
'msgbox(strcomputer & " did not reply" & vbcrlf & vbcrlf & _
'"Please check the name and try again")
else
set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & _
strComputer & "\root\cimv2")
Set colSettings = objWMIService.ExecQuery("Select * from Win32_ComputerSystem")
For Each objComputer in colSettings
objStream.WriteLine objComputer.name & "," & objcomputer.username & "," & objcomputer.domain _
& "," & strcomputer
'msgbox("System Name: " & objComputer.Name & vbcrlf & "User Logged in : " & _
'objcomputer.username & vbcrlf & "Domain: " & objComputer.Domain)
Next
end if
next
end if
Next
Msgbox("Done Collecting")
set objwmiservice = nothing
set colsettings = nothing
set objping = nothing
You use the EVIL global On Error Resume Next. That means: all errors are ignored/hidden and the script continues (more or less happily) in a for all practical purposes undefined state. Demo script:
Option Explicit
Dim a : a = Array(1,0,2)
Bad a
Good a
Sub Bad(a)
Dim i, n
On Error Resume Next
For i = 0 To UBound(a)
n = 4712 / a(i)
WScript.Echo "Bad", i, a(i), n
Next
End Sub
Sub Good(a)
Dim i, n
For i = 0 To UBound(a)
On Error Resume Next
n = 4712 / a(i)
If Err.Number Then n = "value to use in case of error"
On Error GoTo 0
WScript.Echo "Good", i, a(i), n
Next
End Sub
output:
cscript oern.vbs
Bad 0 1 4712
Bad 1 0 4712 <--- assignment failed, 'old' value of n retained, no clue about problem
Bad 2 2 2356
Good 0 1 4712
Good 1 0 value to use in case of error
Good 2 2 2356
The strictly local OERN makes sure that the specific problem (division by zero, ping failure) is dealt with, and all other exceptions are reported, so the program can be improved.
further food for thought
Your WMI call variables need to be reset to nothing before you set them again. This script should work better.
On Error Resume Next
Dim FSO
Dim objStream
Const TriStateFalse = 0
Const FILE_NAME = "Users.csv"
Set FSO = CreateObject("Scripting.FileSystemObject")
Set objStream = FSO.CreateTextFile(FILE_NAME, _
True, TristateFalse)
strSubnetPrefix = "192.168.1."
intBeginSubnet = 1
intEndSubnet = 254
For i = intBeginSubnet To intEndSubnet
strComputer = strSubnetPrefix & i
'strcomputer = inputbox("Enter Computer Name or IP")
if strcomputer = "" then
wscript.quit
else
Set objPing = GetObject("winmgmts:{impersonationLevel=impersonate}").ExecQuery _
("select * from Win32_PingStatus where address = '" & strcomputer & "'")
For Each objStatus in objPing
If IsNull(objStatus.StatusCode) or objStatus.StatusCode<>0 Then
'request timed out
'msgbox(strcomputer & " did not reply" & vbcrlf & vbcrlf & _
'"Please check the name and try again")
else
set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & _
strComputer & "\root\cimv2")
Set colSettings = objWMIService.ExecQuery("Select * from Win32_ComputerSystem")
For Each objComputer in colSettings
objStream.WriteLine objComputer.name & "," & objcomputer.username & "," & objcomputer.domain _
& "," & strcomputer
'msgbox("System Name: " & objComputer.Name & vbcrlf & "User Logged in : " & _
'objcomputer.username & vbcrlf & "Domain: " & objComputer.Domain)
Next
set objwmiservice = nothing
set colsettings = nothing
end if
next
end if
set objping = nothing
Next
Msgbox("Done Collecting")

VB Scripting to excel

I am a help desk technical at my company and I am trying to create a vb login script that would gather various things about the user and computer and create or amend a excel spread sheet on a network drive. A little about my background with programming, I am not a programmer. My knowledge is limited but I do understand some programming logic. So far I have been able to Frankenstein together this vbs script from various sources online with even some of my very own programming. Here is my snag. I want to list all of the network drives of an user to a single cell within excel. I've tried everything with no success.
The closest I can get is it listing just one (the last) network drive. The other issue I've been having is that it will not list any of my member of groups from AD. I know I am a super novice but I am willing to learn and understand. Any help would be great!
Here is my code:
Set WshShell = WScript.CreateObject("wscript.shell")
Set objArgs = WScript.Arguments
Set fso = CreateObject("Scripting.FileSystemObject")
Set oShell = CreateObject("wscript.Shell")
Set env = oShell.environment("Process")
strComputer = env.Item("Computername")
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
Set objWorkbook = objExcel.Workbooks.Add()
Set objWorksheet = objWorkbook.Worksheets(1)
objExcel.worksheets(2).delete
objExcel.worksheets(2).delete
objExcel.ActiveWorkbook.Windows(1).Caption = OutputFile
strOut = ""
getOSInfo
Sub getOSInfo()
On Error Resume Next
objExcel.worksheets(1).Activate
objExcel.worksheets(1).Name = "Computer Info"
objExcel.Cells(1, 1).Value = "Computer Name"
objExcel.Cells(2, 1).Value = "Computer Name from system"
objExcel.Cells(3, 1).Value = "IP(s) from system"
objExcel.Cells(4, 1).Value = "Logon Name"
objExcel.Cells(5, 1).Value = "Operating System"
objExcel.Cells(6, 1).Value = "Last Bootup Time"
objExcel.Cells(7, 1).Value = "Install Date"
objExcel.Cells(8, 1).Value = "Manufacturer"
objExcel.Cells(9, 1).Value = "Serial Number"
objExcel.Cells(10, 1).Value = "Model"
objExcel.Cells(11, 1).Value = "Mapped Drives"
objExcel.Cells(12, 1).Value = "Member of Group(s)"
objExcel.Cells(13, 1).Value = "Amt. of Storage Allocated"
objExcel.Cells(14, 1).Value = "# of Processors"
objExcel.Cells(15, 1).Value = "Processor Type"
objExcel.Cells(16, 1).Value = "Memory (GB)"
colVar=2
Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
If Err.Number <> 0 Then
objExcel.Cells(1, colVar).Value = strComputer
objExcel.Cells(2, colVar).Value = "Error # " & CStr(Err.Number) & " " & Err.Description
printout "Error # " & CStr(Err.Number) & " " & Err.Description
colVar = colVar+1
Err.Clear
Else
objExcel.ActiveWorkbook.Windows(1).Caption = "Getting Win32_OperatingSystem for " & strComputer
Set colOperatingSystems = objWMIService.ExecQuery ("Select * from Win32_OperatingSystem")
objExcel.ActiveWorkbook.Windows(1).Caption = "Getting Win32_BIOS for " & strComputer
Set colBIOS = objWMIService.ExecQuery ("Select * from Win32_BIOS")
objExcel.ActiveWorkbook.Windows(1).Caption = "Getting Win32_ComputerSystem for " & strComputer
Set colComputerSystem = objWMIService.ExecQuery ("Select * from Win32_ComputerSystem")
objExcel.ActiveWorkbook.Windows(1).Caption = "Getting Win32_NetworkAdapterConfiguration for " & strComputer
Set colNetworkAdapterConfiguration = objWMIService.ExecQuery ("Select * from Win32_NetworkAdapterConfiguration")
objExcel.ActiveWorkbook.Windows(1).Caption = "Getting Win32_MappedLogicalDisk for " & strComputer
Set objNetwork = WScript.CreateObject("WScript.Network")
objExcel.ActiveWorkbook.Windows(1).Caption = "Getting Win32_Processor info for " & strComputer
Set colProc = objWMIService.ExecQuery("Select * from Win32_Processor")
For Each objOS In colOperatingSystems
objExcel.ActiveWorkbook.Windows(1).Caption = "Setting Computer Name for " & strComputer
objExcel.Cells(1, colVar).Value = strComputer
objExcel.ActiveWorkbook.Windows(1).Caption = "Setting Last Boot Time for " & strComputer
Set dtmConvertedDate = CreateObject("WbemScripting.SWbemDateTime")
dtmConvertedDate.Value = objOS.InstallDate
dtmInstallDate = dtmConvertedDate.GetVarDate
objExcel.Cells(7, colVar).Value = dtmInstallDate
tempArray = Split(objOS.name, "|")
objExcel.Cells(6, colVar).Value = tempArray(0)
dtmConvertedDate.Value = objOS.LastBootUpTime
dtmBootTime = dtmConvertedDate.GetVarDate
objExcel.Cells(5, colVar).Value = dtmBootTime
Next
For Each objBIOS In colBIOS
objExcel.ActiveWorkbook.Windows(1).Caption = "Setting BIOS info for " & strComputer
objExcel.Cells(9, colVar).Value = objBIOS.SerialNumber
Next
For Each objCS In colComputerSystem
objExcel.ActiveWorkbook.Windows(1).Caption = "Setting Manufacturer info for " & strComputer
objExcel.Cells(8, colVar).Value = objCS.Manufacturer
objExcel.ActiveWorkbook.Windows(1).Caption = "Setting Model info for " & strComputer
objExcel.Cells(10, colVar).Value = objCS.Model
objExcel.ActiveWorkbook.Windows(1).Caption = "Setting name from WMI for " & strComputer
objExcel.Cells(2, colVar).Value = objCS.name
objExcel.ActiveWorkbook.Windows(1).Caption = "Setting Total Physical Memory for " & strComputer
objExcel.Cells(16, colVar).Value = Round(objCS.TotalPhysicalMemory/1024/1024/1024,2)
Next
For Each objNetAdapter In colNetworkAdapterConfiguration
objExcel.ActiveWorkbook.Windows(1).Caption = "Getting IP Addresses for " & strComputer
ipAddress = objNetAdapter.ipaddress
For i = 0 To UBound(ipaddress)
If iplist = "" Then
iplist = ipaddress(i)
Else
iplist = iplist & ", " & ipaddress(i)
End If
Next
objExcel.Cells(3, colVar).Value = iplist
Next
Set colDrives = objNetwork.EnumNetworkDrives
For i = 0 to colDrives.Count-1 Step 2
objExcel.Cells(11, colVar).Value = colDrives.Item(i) & vbTab & colDrives.Item (i + 1)
Next
Err.Clear
strUser = strComputer & "$"
objExcel.ActiveWorkbook.Windows(1).Caption = "Getting AD Group info for " & strComputer
Set objRoot = GetObject("LDAP://RootDSE")
defaultNC = objRoot.Get("defaultnamingcontext")
computerDN = FindUser(strUser, defaultNC)
ouarray = Split(computerDN,",")
For i = 1 To UBound(ouarray)
If ou = "" Then
ou = ouarray(i)
Else
ou = ou & "," & ouarray(i)
End If
Next
Set objWMI = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colItems = objWMI.ExecQuery("Select * from Win32_ComputerSystem")
For Each objItem In colItems
strUsers = objItem.UserName
Next
objExcel.Cells(4, colVar).Value = strUsers 'ou
Set dicSeenGroup = CreateObject("Scripting.Dictionary")
strGroups = DisplayGroups(computerDN,"",dicSeenGroup)
aryGroups = Split(strGroups,"CN=")
strGroups = ""
For i = 2 To UBound(aryGroups)
strGroups = strGroups & ", " & aryGroups(i)
Next
objExcel.Cells(12, colVar).Value = Right(strGroups,Len(strGroups) -2)
Err.Clear
stroutput = getDriveLettersAndSize(strComputer)
objExcel.Cells(13, colVar).Value = Left(stroutput,Len(stroutput)-2)
ProcCount = 0
objExcel.ActiveWorkbook.Windows(1).Caption = "Setting number of processors for " & strComputer
For Each processor In colProc
ProcCount = ProcCount + 1
ProcName = processor.name
Next
objExcel.Cells(14, colVar).Value = ProcCount
objExcel.Cells(15, colVar).Value = Trim(ProcName)
strOut = ""
iplist = ""
ou = ""
colVar = colVar+1
End If
objExcel.Cells.Select
objExcel.Cells.EntireColumn.AutoFit
objExcel.Range("B2").Select
objExcel.ActiveWindow.FreezePanes = True
objWorksheet.Columns("B:B").HorizontalAlignment = -4131
objExcel.ActiveWorkbook.Windows(1).Caption = "Finished gathering computer info"
End Sub
Function FindUser(Byval UserName, Byval Domain)
On Error Resume Next
Set cn = CreateObject("ADODB.Connection")
Set cmd = CreateObject("ADODB.Command")
Set rs = CreateObject("ADODB.Recordset")
cn.open "Provider=ADsDSOObject;"
cmd.activeconnection=cn
cmd.commandtext="SELECT ADsPath FROM 'LDAP://" & Domain & "' WHERE sAMAccountName = '" & UserName & "'"
Set rs = cmd.Execute
If Err<>0 Then
FindUser="Error connecting to Active Directory Database:" & Err.description
'wscript.quit
Else
If Not rs.BOF And Not rs.EOF Then
rs.MoveFirst
FindUser = rs(0)
Else
FindUser = "Not Found"
End If
End If
cn.close
End Function
Function DisplayGroups ( strObjectADsPath, strSpaces, dicSeenGroup)
Set objObject = GetObject(strObjectADsPath)
'strOut must be global variable
strOut = strOut & strSpaces & objObject.Name
On Error Resume Next ' Doing this to avoid an error when memberOf is empty
If IsArray( objObject.Get("memberOf") ) Then
colGroups = objObject.Get("memberOf")
Else
colGroups = Array( objObject.Get("memberOf") )
End If
For Each strGroupDN In colGroups
If Not dicSeenGroup.Exists(strGroupDN) Then
dicSeenGroup.Add strGroupDN, 1
DisplayGroups "LDAP://" & strGroupDN, strSpaces & " ", dicSeenGroup
End If
Next
Err.Clear
DisplayGroups = strOut
End Function
Function getDriveLettersAndSize(strComputer)
On Error Resume Next
Set objWMIService = GetObject("winmgmts://" & strComputer & "/root/cimv2")
If Err.Number Then
getDriveLettersAndSize = "Error # " & CStr(Err.Number) & " " & Err.Description & " "
Err.Clear
Else
On Error Goto 0
Set colItems = objWMIService.ExecQuery("Select * from Win32_LogicalDisk where DriveType=3", , 48)
For Each objItem In colItems
getDriveLettersAndSize = getDriveLettersAndSize & objItem.Name & " " & Round(getDriveSizeTotal(strComputer,objItem.Name)/1024/1024/1024,2) & "GB, "
Next
End If
End Function
Function getDriveSizeTotal(strComputer, drvLetter)
On Error Resume Next
Set objWMIService = GetObject("winmgmts://" & strComputer & "/root/cimv2")
strTemp = strComputer
If Err.Number Then
getDriveSizeTotal = "0"
Err.Clear
Else
On Error Goto 0
Set colItems = objWMIService.ExecQuery("Select * from Win32_LogicalDisk where DriveType=3", , 48)
For Each objItem In colItems
If UCase(objItem.Name) = UCase(drvLetter) Then
getDriveSizeTotal = objItem.Size
End If
Next
End If
End Function
I don't intend to work through your code so I shall concentrate on the question:
I want to list all of the network drives of an user to a single cell
within excel.
You would use string concatenation with the ampersand & operator:
Range("A1").Value = Range("A1").Value & " " & "C:"
Replace "C:" with whatever variable contains the current drive letter.
To solve the drives problem (without a leading blank):
>> Set objNetwork = WScript.CreateObject("WScript.Network")
>> Set colDrives = objNetwork.EnumNetworkDrives
>> sDrives = ""
>> For i = 0 to colDrives.Count-1 Step 2
>> sDrives = sDrives & vbTab & colDrives.Item(i)
>> Next
>> sDrives = Mid(sDrives, 2)
>> WScript.Echo """" & sDrives & """"
Put sDrives into the cell (once).

Export SYS Info from a VBS to Excel

Just wondering if anyone can help me achieve this. I have 2 VBS scripts which can show me PC Sysinfo and monitor info when I specify machine name or IP address. However I would like to modify this so I can run 1 VBS to get both info (PC Sysinfo + monitor info) then export to an MS Excel file. Currently you can only input 1 PC name or IP address. Is there a way to modify so I can batch process to get all the PC info in the domain?
PC Sysinfo VBS script
strComputer = inputbox("Type the name of the computer with out \\ or an IP address to find out the service tag")
rem strComputer = "10.12.102.109"
if strComputer = "" then wscript.quit
Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colSMBIOS = objWMIService.ExecQuery ("Select * from Win32_SystemEnclosure")
For Each objSMBIOS in colSMBIOS
rem Wscript.Echo "Service tag (serial number): " & objSMBIOS.SerialNumber
strSN = objSMBIOS.SerialNumber
Next
rem strComputer = "."
Set objSWbemServices = GetObject("winmgmts:\\" & strComputer)
Set colSWbemObjectSet = _
objSWbemServices.InstancesOf("Win32_LogicalMemoryConfiguration")
For Each objSWbemObject In colSWbemObjectSet
rem Wscript.Echo "Total Physical Memory (kb): " & _
rem objSWbemObject.TotalPhysicalMemory
strMemory = objSWbemObject.TotalPhysicalMemory
Next
Set colOperatingSystems = objSWbemServices.InstancesOf("Win32_OperatingSystem")
For Each objOperatingSystem In colOperatingSystems
OSName = objOperatingSystem.Name
OSVersion = objOperatingSystem.Version
OSSevPac= objOperatingSystem.ServicePackMajorVersion & _
"." & objOperatingSystem.ServicePackMinorVersion
Next
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colSettings = objWMIService.ExecQuery _
("SELECT * FROM Win32_OperatingSystem")
For Each objOperatingSystem in colSettings
AvaMem = objOperatingSystem.FreePhysicalMemory
Next
Set colSettings = objWMIService.ExecQuery _
("SELECT * FROM Win32_ComputerSystem")
For Each objComputer in colSettings
CmpNam = objComputer.Name
CmpMnf = objComputer.Manufacturer
CmpMdl = objComputer.Model
Next
Set colSettings = objWMIService.ExecQuery _
("SELECT * FROM Win32_Processor")
For Each objProcessor in colSettings
PrcDsc = objProcessor.Description
Next
Set colSettings = objWMIService.ExecQuery _
("SELECT * FROM Win32_BIOS")
For Each objBIOS in colSettings
BIOS = objBIOS.Version
Next
Rem --------------------
Set colAdapters = objWMIService.ExecQuery _
("Select * From Win32_NetworkAdapterConfiguration Where IPEnabled = True")
For Each oAdapter in colAdapters
For Each sIPAddress in oAdapter.IPAddress
If sIPAddress <> "0.0.0.0" Then
IP = sIPAddress
MAC = oAdapter.MACAddress
EXIT FOR
End If
Next
Next
Rem
rem ____________________
MsgBox "Hardware" & vbCrLf & _
" Service Tag: " & strSN & vbCrLf & _
" Total Memory(KB): " & strMemory & vbCrLf & _
" Available Memory(KB): " & AvaMem & vbCrLf & _
" Computer Name: " & CmpNam & vbCrLf & _
" System Manufacturer: " & CmpMnf & vbCrLf & _
" System Model: " & CmpMdl & vbCrLf & _
" Processor: " & PrcDsc & vbCrLf & _
" BIOS Version: " & BIOS & vbCrLf & vbCrLf & _
"OS" & vbCrLf & _
" OS Name: " & OSName & vbCrLf & _
" Version: " & OSVersion & vbCrLf & _
" Service Pack: " & OSSevPac & vbCrLf & vbCrLf &_
" Network" & vbCrLf & _
" IP Address: " & IP & vbcrlf & _
" MAC: " & MAC _
,0, strComputer & " - System Information"
Rem
Monitor VBS script
'
'==========================================================================
Option Explicit
Dim WshShell
Set WshShell = WScript.CreateObject("WScript.Shell")
Dim strComputer, message
Dim intMonitorCount
Dim oRegistry, sBaseKey, sBaseKey2, sBaseKey3, skey, skey2, skey3
Dim sValue
dim i, iRC, iRC2, iRC3
Dim arSubKeys, arSubKeys2, arSubKeys3, arrintEDID
Dim strRawEDID
Dim ByteValue, strSerFind, strMdlFind
Dim intSerFoundAt, intMdlFoundAt, findit
Dim tmp, tmpser, tmpmdl, tmpctr
Dim batch, bHeader
batch = False
If WScript.Arguments.Count = 1 Then
strComputer = WScript.Arguments(0)
batch = True
Else
strComputer = wshShell.ExpandEnvironmentStrings("%COMPUTERNAME%")
strComputer = InputBox("Check Monitor info for what PC","PC Name?",strComputer)
End If
If strcomputer = "" Then WScript.Quit
strComputer = UCase(strComputer)
If batch Then
Dim fso,logfile, appendout
logfile = wshShell.ExpandEnvironmentStrings("%userprofile%") & "\desktop\MonitorInfo.csv"
'setup Log
Const ForAppend = 8
Set fso = CreateObject("Scripting.FileSystemObject")
If Not fso.FileExists(logfile) Then bHeader = True
set appendout = fso.OpenTextFile(logfile, ForAppend, True)
If bHeader Then
appendout.writeline "Computer,Model,Serial #,Vendor ID,Manufacture Date,Messages"
End If
End If
Dim strarrRawEDID()
intMonitorCount=0
Const HKLM = &H80000002 'HKEY_LOCAL_MACHINE
'get a handle to the WMI registry object
On Error Resume Next
Set oRegistry = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "/root/default:StdRegProv")
If Err <> 0 Then
If batch Then
EchoAndLog strComputer & ",,,,," & Err.Description
Else
MsgBox "Failed. " & Err.Description,vbCritical + vbOKOnly,strComputer
WScript.Quit
End If
End If
sBaseKey = "SYSTEM\CurrentControlSet\Enum\DISPLAY\"
'enumerate all the keys HKLM\SYSTEM\CurrentControlSet\Enum\DISPLAY\
iRC = oRegistry.EnumKey(HKLM, sBaseKey, arSubKeys)
For Each sKey In arSubKeys
'we are now in the registry at the level of:
'HKLM\SYSTEM\CurrentControlSet\Enum\DISPLAY\<VESA_Monitor_ID\
'we need to dive in one more level and check the data of the "HardwareID" value
sBaseKey2 = sBaseKey & sKey & "\"
iRC2 = oRegistry.EnumKey(HKLM, sBaseKey2, arSubKeys2)
For Each sKey2 In arSubKeys2
'now we are at the level of:
'HKLM\SYSTEM\CurrentControlSet\Enum\DISPLAY\<VESA_Monitor_ID\<PNP_ID>\
'so we can check the "HardwareID" value
oRegistry.GetMultiStringValue HKLM, sBaseKey2 & sKey2 & "\", "HardwareID", sValue
for tmpctr=0 to ubound(svalue)
If lcase(left(svalue(tmpctr),8))="monitor\" then
'If it is a monitor we will check for the existance of a control subkey
'that way we know it is an active monitor
sBaseKey3 = sBaseKey2 & sKey2 & "\"
iRC3 = oRegistry.EnumKey(HKLM, sBaseKey3, arSubKeys3)
For Each sKey3 In arSubKeys3
'Kaplan edit
strRawEDID = ""
If skey3="Control" Then
'If the Control sub-key exists then we should read the edid info
oRegistry.GetBinaryValue HKLM, sbasekey3 & "Device Parameters\", "EDID", arrintEDID
If vartype(arrintedid) <> 8204 then 'and If we don't find it...
strRawEDID="EDID Not Available" 'store an "unavailable message
else
for each bytevalue in arrintedid 'otherwise conver the byte array from the registry into a string (for easier processing later)
strRawEDID=strRawEDID & chr(bytevalue)
Next
End If
'now take the string and store it in an array, that way we can support multiple monitors
redim preserve strarrRawEDID(intMonitorCount)
strarrRawEDID(intMonitorCount)=strRawEDID
intMonitorCount=intMonitorCount+1
End If
Next
End If
Next
Next
Next
'*****************************************************************************************
'now the EDID info for each active monitor is stored in an array of strings called strarrRawEDID
'so we can process it to get the good stuff out of it which we will store in a 5 dimensional array
'called arrMonitorInfo, the dimensions are as follows:
'0=VESA Mfg ID, 1=VESA Device ID, 2=MFG Date (M/YYYY),3=Serial Num (If available),4=Model Descriptor
'5=EDID Version
'*****************************************************************************************
On Error Resume Next
dim arrMonitorInfo()
redim arrMonitorInfo(intMonitorCount-1,5)
dim location(3)
for tmpctr=0 to intMonitorCount-1
If strarrRawEDID(tmpctr) <> "EDID Not Available" then
'*********************************************************************
'first get the model and serial numbers from the vesa descriptor
'blocks in the edid. the model number is required to be present
'according to the spec. (v1.2 and beyond)but serial number is not
'required. There are 4 descriptor blocks in edid at offset locations
'&H36 &H48 &H5a and &H6c each block is 18 bytes long
'*********************************************************************
location(0)=mid(strarrRawEDID(tmpctr),&H36+1,18)
location(1)=mid(strarrRawEDID(tmpctr),&H48+1,18)
location(2)=mid(strarrRawEDID(tmpctr),&H5a+1,18)
location(3)=mid(strarrRawEDID(tmpctr),&H6c+1,18)
'you can tell If the location contains a serial number If it starts with &H00 00 00 ff
strSerFind=chr(&H00) & chr(&H00) & chr(&H00) & chr(&Hff)
'or a model description If it starts with &H00 00 00 fc
strMdlFind=chr(&H00) & chr(&H00) & chr(&H00) & chr(&Hfc)
intSerFoundAt=-1
intMdlFoundAt=-1
for findit = 0 to 3
If instr(location(findit),strSerFind)>0 then
intSerFoundAt=findit
End If
If instr(location(findit),strMdlFind)>0 then
intMdlFoundAt=findit
End If
Next
'If a location containing a serial number block was found then store it
If intSerFoundAt<>-1 then
tmp=right(location(intSerFoundAt),14)
If instr(tmp,chr(&H0a))>0 then
tmpser=trim(left(tmp,instr(tmp,chr(&H0a))-1))
Else
tmpser=trim(tmp)
End If
'although it is not part of the edid spec it seems as though the
'serial number will frequently be preceeded by &H00, this
'compensates for that
If left(tmpser,1)=chr(0) then tmpser=right(tmpser,len(tmpser)-1)
else
tmpser="Not Found"
End If
'If a location containing a model number block was found then store it
If intMdlFoundAt<>-1 then
tmp=right(location(intMdlFoundAt),14)
If instr(tmp,chr(&H0a))>0 then
tmpmdl=trim(left(tmp,instr(tmp,chr(&H0a))-1))
else
tmpmdl=trim(tmp)
End If
'although it is not part of the edid spec it seems as though the
'serial number will frequently be preceeded by &H00, this
'compensates for that
If left(tmpmdl,1)=chr(0) then tmpmdl=right(tmpmdl,len(tmpmdl)-1)
else
tmpmdl="Not Found"
End If
'**************************************************************
'Next get the mfg date
'**************************************************************
Dim tmpmfgweek,tmpmfgyear,tmpmdt
'the week of manufacture is stored at EDID offset &H10
tmpmfgweek=asc(mid(strarrRawEDID(tmpctr),&H10+1,1))
'the year of manufacture is stored at EDID offset &H11
'and is the current year -1990
tmpmfgyear=(asc(mid(strarrRawEDID(tmpctr),&H11+1,1)))+1990
'store it in month/year format
tmpmdt=month(dateadd("ww",tmpmfgweek,datevalue("1/1/" & tmpmfgyear))) & "/" & tmpmfgyear
'**************************************************************
'Next get the edid version
'**************************************************************
'the version is at EDID offset &H12
Dim tmpEDIDMajorVer, tmpEDIDRev, tmpVer
tmpEDIDMajorVer=asc(mid(strarrRawEDID(tmpctr),&H12+1,1))
'the revision level is at EDID offset &H13
tmpEDIDRev=asc(mid(strarrRawEDID(tmpctr),&H13+1,1))
'store it in month/year format
tmpver=chr(48+tmpEDIDMajorVer) & "." & chr(48+tmpEDIDRev)
'**************************************************************
'Next get the mfg id
'**************************************************************
'the mfg id is 2 bytes starting at EDID offset &H08
'the id is three characters long. using 5 bits to represent
'each character. the bits are used so that 1=A 2=B etc..
'
'get the data
Dim tmpEDIDMfg, tmpMfg
dim Char1, Char2, Char3
Dim Byte1, Byte2
tmpEDIDMfg=mid(strarrRawEDID(tmpctr),&H08+1,2)
Char1=0 : Char2=0 : Char3=0
Byte1=asc(left(tmpEDIDMfg,1)) 'get the first half of the string
Byte2=asc(right(tmpEDIDMfg,1)) 'get the first half of the string
'now shift the bits
'shift the 64 bit to the 16 bit
If (Byte1 and 64) > 0 then Char1=Char1+16
'shift the 32 bit to the 8 bit
If (Byte1 and 32) > 0 then Char1=Char1+8
'etc....
If (Byte1 and 16) > 0 then Char1=Char1+4
If (Byte1 and 8) > 0 then Char1=Char1+2
If (Byte1 and 4) > 0 then Char1=Char1+1
'the 2nd character uses the 2 bit and the 1 bit of the 1st byte
If (Byte1 and 2) > 0 then Char2=Char2+16
If (Byte1 and 1) > 0 then Char2=Char2+8
'and the 128,64 and 32 bits of the 2nd byte
If (Byte2 and 128) > 0 then Char2=Char2+4
If (Byte2 and 64) > 0 then Char2=Char2+2
If (Byte2 and 32) > 0 then Char2=Char2+1
'the bits for the 3rd character don't need shifting
'we can use them as they are
Char3=Char3+(Byte2 and 16)
Char3=Char3+(Byte2 and 8)
Char3=Char3+(Byte2 and 4)
Char3=Char3+(Byte2 and 2)
Char3=Char3+(Byte2 and 1)
tmpmfg=chr(Char1+64) & chr(Char2+64) & chr(Char3+64)
'**************************************************************
'Next get the device id
'**************************************************************
'the device id is 2bytes starting at EDID offset &H0a
'the bytes are in reverse order.
'this code is not text. it is just a 2 byte code assigned
'by the manufacturer. they should be unique to a model
Dim tmpEDIDDev1, tmpEDIDDev2, tmpDev
tmpEDIDDev1=hex(asc(mid(strarrRawEDID(tmpctr),&H0a+1,1)))
tmpEDIDDev2=hex(asc(mid(strarrRawEDID(tmpctr),&H0b+1,1)))
If len(tmpEDIDDev1)=1 then tmpEDIDDev1="0" & tmpEDIDDev1
If len(tmpEDIDDev2)=1 then tmpEDIDDev2="0" & tmpEDIDDev2
tmpdev=tmpEDIDDev2 & tmpEDIDDev1
'**************************************************************
'finally store all the values into the array
'**************************************************************
'Kaplan adds code to avoid duplication...
If Not InArray(tmpser,arrMonitorInfo,3) Then
arrMonitorInfo(tmpctr,0)=tmpmfg
arrMonitorInfo(tmpctr,1)=tmpdev
arrMonitorInfo(tmpctr,2)=tmpmdt
arrMonitorInfo(tmpctr,3)=tmpser
arrMonitorInfo(tmpctr,4)=tmpmdl
arrMonitorInfo(tmpctr,5)=tmpVer
End If
End If
Next
'For now just a simple screen print will suffice for output.
'But you could take this output and write it to a database or a file
'and in that way use it for asset management.
i = 0
for tmpctr = 0 to intMonitorCount-1
If arrMonitorInfo(tmpctr,1) <> "" And arrMonitorInfo(tmpctr,0) <> "PNP" Then
If batch Then
EchoAndLog strComputer & "," & arrMonitorInfo(tmpctr,4) & "," & _
arrMonitorInfo(tmpctr,3)& "," & arrMonitorInfo(tmpctr,0) & "," & _
arrMonitorInfo(tmpctr,2)
Else
message = message & "Monitor " & chr(i+65) & ")" & VbCrLf & _
"Model Name: " & arrMonitorInfo(tmpctr,4) & VbCrLf & _
"Serial Number: " & arrMonitorInfo(tmpctr,3)& VbCrLf & _
"VESA Manufacturer ID: " & arrMonitorInfo(tmpctr,0) & VbCrLf & _
"Manufacture Date: " & arrMonitorInfo(tmpctr,2) & VbCrLf & VbCrLf
'wscript.echo ".........." & "Device ID: " & arrMonitorInfo(tmpctr,1)
'wscript.echo ".........." & "EDID Version: " & arrMonitorInfo(tmpctr,5)
i = i + 1
End If
End If
Next
If not batch Then
MsgBox message, vbInformation + vbOKOnly,strComputer & " Monitor Info"
End If
Function InArray(strValue,List,Col)
Dim i
For i = 0 to UBound(List)
If List(i,col) = cstr(strValue) Then
InArray = True
Exit Function
End If
Next
InArray = False
End Function
Sub EchoAndLog (message)
'Echo output and write to log
Wscript.Echo message
AppendOut.WriteLine message
End Sub
You can loop through all the computers in the domain using LDAP using code similar to this:
Const ADS_SCOPE_SUBTREE = 2
Set conn = CreateObject("ADODB.Connection")
Set cmd = CreateObject("ADODB.Command")
conn.Provider = "ADsDSOObject"
conn.Open "Active Directory Provider"
Set cmd.ActiveConnection = conn
cmd.Properties("Page Size") = 1000
cmd.Properties("Searchscope") = ADS_SCOPE_SUBTREE
cmd.CommandText = "SELECT Name FROM 'LDAP://dc=test,dc=com' WHERE objectCategory='computer'"
Set rec = cmd.Execute
rec.MoveFirst
Do Until rec.EOF
Wscript.Echo rec.Fields("Name").Value
rec.MoveNext
Loop
You'll have to change LDAP://dc=test,dc=com to a binding string that suits you.
And then if you refactor your current code in those 2 scripts to be inside at least a couple (though I'd suggest trying to change your code so that each separate value that you retrieve by a separate piece of code would be in it's own function as well and have those functions be called by the procedures as needed) of procedures you could just call those procedures instead of doing Wscript.Echo rec.Fields("Name").Value.
To create the Excel files you've got various options, the easiest one would probably be to use FSO (FileSystemObject) to write the values to CSV files, instead of showing the in Message Boxes, that could then be easily be opened by Excel.
Otherwise if you want to do something more advanced you could automate Excel to do it, see the following article for details about that: How to automate Excel from a client-side VBScript.

Resources