VBS output in column format - vbscript

I am trying to have my .vbs output be put into columns. However, when I try write the code to organize the output into columns I continue to get an error - Invalid Procedure call or argument: 'Space'
I'm looking for some help on this, thanks!!
Call FindPCsThatUserLoggedInto
Sub FindPCsThatUserLoggedInto()
strUser = InputBox("Enter First Name")
strLast = InputBox("Enter Last Name")
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
objCommand.Properties("Page Size") = 1000
objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE
's = "Name" & Chr(9) & "Account Name" & Chr(9) & "Location" & Chr(10) & Chr(13)
's = s & "----" & Chr(9) & "------------" & Chr(9) & "--------" & Chr(10) & Chr(13)
s = RightJustified("Name", 10) & _
RightJustified("Account Name", 15) & _
RightJustified("Location", 15) & _
vbCrLf
objCommand.CommandText = "SELECT ADSPath FROM 'LDAP://dc=hc,dc=company,dc=com' WHERE givenName = '" & strUser & "*' AND sn = '" & strLast & "*'"
Set objRecordSet = objCommand.Execute
If objRecordSet.Recordcount > 0 Then
objRecordSet.MoveFirst
Do Until objRecordSet.EOF
Set objUser = GetObject(objRecordSet.Fields("ADSPath").Value)
's = s & objUser.DisplayName & Chr(9) & objUser.samaccountname & Chr(9) & objUser.PhysicalDeliveryOfficeName & Chr(10) & Chr(13)
' objRecordSet.MoveNext
s = s & _
RightJustified(objUser.DisplayName, 10) & _
RightJustified(objUser.samaccountname, 15) & _
RightJustified(objUser.PhysicalDeliveryOfficeName, 15) & _
vbCrLf
Loop
MsgBox s
Else
MsgBox "No users matching that criteria exist in the HC domain in AD."
End If
End Sub
Function RightJustified(ColumnValue, ColumnWidth)
RightJustified = Space(ColumnWidth - Len(ColumnValue)) & ColumnValue
End Function
This is the code that I added to organize the outputs into columns:
s = RightJustified("Name", 10) & _
RightJustified("Account Name", 15) & _
RightJustified("Location", 15) & _
vbCrLf
And
s = s & _
RightJustified(objUser.DisplayName, 10) & _
RightJustified(objUser.samaccountname, 15) & _
RightJustified(objUser.PhysicalDeliveryOfficeName, 15) & _
vbCrLf
Here is my output:

My guess would be that this is a runtime error due to your data exceeding the specified size?
RightJustified(objUser.DisplayName, 10) & _
RightJustified(objUser.samaccountname, 15) & _
RightJustified(objUser.PhysicalDeliveryOfficeName, 15) & _
vbCrLf
Perhaps this change would be needed:
Function RightJustified(ColumnValue, ColumnWidth)
If Len(ColumnValue) > ColumnWidth Then
ColumnValue = Left(ColumnValue,ColumnWidth)
End If
RightJustified = Space(ColumnWidth - Len(ColumnValue)) & ColumnValue
End Function

Related

Checking Installed programs

I need help in finding installed software version, license etc.
the below script works fine but it lists out all the installed softwares.
But am trying to find out a particular software.It gives nice output, can you help me here.
==================================================
'This script outputs to a .tsv file a list of applications installed on the computer
'Output file is software.tsv
'Usage: cscript applications.vbs
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.CreateTextFile("C:\WINDOWS\system32\temp\software.tsv", True)
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colSoftware = objWMIService.ExecQuery _
("Select * from Win32_Product")
objTextFile.WriteLine "Caption" & vbtab & _
"Description" & vbtab & "Identifying Number" & vbtab & _
"Install Date" & vbtab & "Install Location" & vbtab & _
"Install State" & vbtab & "Name" & vbtab & _
"Package Cache" & vbtab & "SKU Number" & vbtab & "Vendor" & vbtab _
& "Version"
For Each objSoftware in colSoftware
objTextFile.WriteLine objSoftware.Caption & vbtab & _
objSoftware.Description & vbtab & _
objSoftware.IdentifyingNumber & vbtab & _
objSoftware.InstallDate2 & vbtab & _
objSoftware.InstallLocation & vbtab & _
objSoftware.InstallState & vbtab & _
objSoftware.Name & vbtab & _
objSoftware.PackageCache & vbtab & _
objSoftware.SKUNumber & vbtab & _
objSoftware.Vendor & vbtab & _
objSoftware.Version
Next
objTextFile.Close
======================================================
i just looking for details of C:\Program Files\HP\hponcfg\hponcfg.exe and i do not bother about other installed softwares, by default the above script gives the details of all the softwares, but i just do not need that.
where do i insert this line in the script.??
regards,
Dharanesh,
Check this modification, i tried it with name Google, so check it if retruns for you what do you expect or not ?
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set Ws = CreateObject("WScript.Shell")
LogFile = "software.tsv"
if objFSO.FileExists(LogFile) Then
objFSO.DeleteFile(LogFile)
End if
Set objTextFile = objFSO.OpenTextFile(LogFile,8,True)
MySoftware = "Google"
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colSoftware = objWMIService.ExecQuery _
("Select * from Win32_Product where Name Like " & CommandLineLike(MySoftware))
objTextFile.WriteLine "Caption" & vbtab & _
"Description" & vbtab & "Identifying Number" & vbtab & _
"Install Date" & vbtab & "Install Location" & vbtab & _
"Install State" & vbtab & "Name" & vbtab & _
"Package Cache" & vbtab & "SKU Number" & vbtab & "Vendor" & vbtab _
& "Version"
For Each objSoftware in colSoftware
objTextFile.WriteLine objSoftware.Caption & vbtab & _
objSoftware.Description & vbtab & _
objSoftware.IdentifyingNumber & vbtab & _
objSoftware.InstallDate2 & vbtab & _
objSoftware.InstallLocation & vbtab & _
objSoftware.InstallState & vbtab & _
objSoftware.Name & vbtab & _
objSoftware.PackageCache & vbtab & _
objSoftware.SKUNumber & vbtab & _
objSoftware.Vendor & vbtab & _
objSoftware.Version
Next
objTextFile.Close
ws.run "Notepad software.tsv"
'**************************************************************************
Function CommandLineLike(MySoftware)
MySoftware = Replace(MySoftware, "\", "\\")
CommandLineLike = "'%" & MySoftware & "%'"
End Function
'**************************************************************************
How to get the extended information of a file ?
For example this vbscript can get the extended information of Firefox.exe :
Option Explicit
Dim fso,ws,RootFolder,LogFile,stFolder,stFile,oShell,oFolder,oFile,i
Set fso = CreateObject("Scripting.FileSystemObject")
Set ws = CreateObject("WScript.Shell")
LogFile = Left(Wscript.ScriptFullName,InstrRev(Wscript.ScriptFullName, ".")) & "txt"
If fso.FileExists(LogFile) Then
fso.DeleteFile(LogFile)
End If
stFolder = Ws.ExpandEnvironmentStrings("%PROGRAMFILES%\Mozilla Firefox")
stFile ="firefox.exe"
Set oShell = CreateObject("Shell.Application")
Set oFolder = oShell.Namespace(stFolder)
Set oFile = oFolder.Items.Item(stFile)
'Displays extended file properties
For i = 0 to 34
WriteLog("[" & i & "] " & oFolder.GetDetailsOf(oFolder.Items, i ) & " : " & oFolder.GetDetailsOf(oFile, i))
Next
ws.run DblQuote(LogFile)
'*********************************************************************************************************************
Sub WriteLog(strText)
Dim fs,ts,LogFile
Const ForAppending = 8
LogFile = Left(Wscript.ScriptFullName, InstrRev(Wscript.ScriptFullName, ".")) & "txt"
Set fs = CreateObject("Scripting.FileSystemObject")
Set ts = fs.OpenTextFile(LogFile,ForAppending,True)
ts.WriteLine strText
ts.Close
End Sub
'*********************************************************************************************************************
Function DblQuote(Str)
DblQuote = Chr(34) & Str & Chr(34)
End Function
'**********************************************************************************************************************
Or if you want to check the version of Firefox installed and if it is uptodate or not try this vbscript :
Option Explicit
Const ForWriting = 2
Const HKEY_CLASSES_ROOT = &H80000000
Const HKEY_CURRENT_USER = &H80000001
Const HKEY_LOCAL_MACHINE = &H80000002
Const HKEY_USERS = &H80000003
Const REG_SZ = 1
Const REG_EXPAND_SZ = 2
Const REG_BINARY = 3
Const REG_DWORD = 4
Const REG_MULTI_SZ = 7
Dim RC , sPath, sNames, iTypes, sValue, objRegistry
Dim ROOT, i, j , msg, sKey, RC1, sKeyNames, fso, Fich
Set fso = CreateObject("Scripting.FileSystemObject")
Set Fich = fso.OpenTextFile("Version.txt", ForWriting, true)
Dim shell : Set shell = CreateObject("WScript.Shell")
sPath = "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\"
ROOT = HKEY_LOCAL_MACHINE
Dim OK
OK = False
Set objRegistry = GetObject("WinMgmts:root\default:StdRegProv")
RC1 = objRegistry.EnumKey(ROOT, sPath, sKeyNames)
If (RC1 = 0) And (Err.Number = 0) And Not IsEmpty(sKeyNames) Then
For j = LBound(sKeyNames) To UBound(sKeyNames)
RC = objRegistry.EnumValues(ROOT, sPath & sKeyNames(j), sNames, iTypes)
If (RC = 0) And (Err.Number = 0) And IsArray(sNames) Then
If VerifTypes(ROOT, sPath & sKeyNames(j), iTypes) And OK Then Fich.WriteLine vbNewLine & sKeyNames(j) & " : "
For i = LBound(iTypes) To UBound(iTypes)
If iTypes(i) = REG_SZ Then
RC = objRegistry.GetStringValue(ROOT , sPath & sKeyNames(J), sNames(i), sValue)
If (LCase(sNames(i)) = "displayname" And sValue <> "") Or (LCase(sNames(i)) = "displayversion" And sValue <> "") Then
If InStr(1,LCase(sValue),"firefox") > 0 Then
msg = msg & sNames(i) & " = " & sValue
OK = True
MsgBox sValue & VbcrLf & "La version installée du soft Firefox est : "& ExtractVersion(sValue),64,"La Version installée du Soft Firefox"
Dim MyVer,NetVersion,URL,ws
MyVer = ExtractVersion(sValue)
URL = "http://www.mozilla.org/fr/firefox/new/"
NetVersion = GetFirefoxMajorVersion(URL)
msgbox NetVersion
If CompareVersions(MyVer,NetVersion) = -1 Then
MsgBox "La dernière version de Firefox est : " & NetVersion & VbCrlf &_
"Il y a une mise à jour en ligne !",48,"Il y a une mise à jour en ligne ! "
set ws = CreateObject("WScript.Shell")
ws.run URL
Else
MsgBox "Firefox est à jour !",64,"Firefox est à jour !"
end if
Fich.Write msg & vbNewLine & "La version installée du soft Firefox est : "& ExtractVersion(sValue) & vbNewLine
End If
End If
OK = False
End If
msg = ""
Next ' pour i
'MsgBox msg
Else
'Msgbox "L'erreur suivante est survenue : " & Err.Description
End If
Next ' pour J
Fich.Close
End If
Shell.run "version.txt"
'******************************************************************************************************************
Function Lsh(ByVal N, ByVal Bits)
Lsh = N * (2 ^ Bits)
End Function
'***************************************************************************************
Function VerifTypes(ROOT, strPath, Types)
' Cette fonction vérifie si la clé (strPath) contient des valeurs
' "DisplayVersion" ou "DisplayName" et qui ne sont pas être vides
' pour ne pas retourner celles qui n'en contiennent pas.
Dim Ret, strNames, Verif, ind
Verif = False
Ret = objRegistry.EnumValues(ROOT, strPath,strNames, Types)
If (Ret = 0) And (Err.Number = 0) And IsArray(strNames) Then
For ind = LBound(strNames) To UBound(strNames)
If LCase(strNames(ind)) = "displayname" Or LCase(strNames(ind)) = "displayversion" Then
Verif = True
Exit For
ELse
Verif = False
End If
Next
End If
VerifTypes = Verif
End Function
'***************************************************************************************
Function ExtractVersion(Data)
Dim objRegex,Match,Matches
Set objRegex = new RegExp
objRegex.Pattern = "\d{2}\.\d"
objRegex.Global = False
objRegex.IgnoreCase = True
Set Matches = objRegex.Execute(Data)
For Each Match in Matches
ExtractVersion = Match.Value
Next
End Function
'***************************************************************************************
Function GetVersionStringAsArray(ByVal Version)
Dim VersionAll, VersionParts, N
VersionAll = Array(0, 0, 0, 0)
VersionParts = Split(Version, ".")
For N = 0 To UBound(VersionParts)
VersionAll(N) = CLng(VersionParts(N))
Next
Dim Hi, Lo
Hi = Lsh(VersionAll(0), 16) + VersionAll(1)
Lo = Lsh(VersionAll(2), 16) + VersionAll(3)
GetVersionStringAsArray = Array(Hi, Lo)
End Function
'***************************************************************************************
' Compares two versions "a.b.c.d". If Version1 < Version2,
' returns -1. If Version1 = Version2, returns 0.
' If Version1 > Version2, returns 1.
Function CompareVersions(ByVal Version1, ByVal Version2)
Dim Ver1, Ver2, Result
Ver1 = GetVersionStringAsArray(Version1)
Ver2 = GetVersionStringAsArray(Version2)
If Ver1(0) < Ver2(0) Then
Result = -1
ElseIf Ver1(0) = Ver2(0) Then
If Ver1(1) < Ver2(1) Then
Result = -1
ElseIf Ver1(1) = Ver2(1) Then
Result = 0
Else
Result = 1
End If
Else
Result = 1
End If
CompareVersions = Result
End Function
'***************************************************************************************
Function GetFirefoxMajorVersion(URL)
Dim Titre,ie,objFSO,Data,OutPut,objRegex,Match,Matches
Titre = "La dernière version de Firefox"
Set ie = CreateObject("InternetExplorer.Application")
Set objFSO = CreateObject("Scripting.FileSystemObject")
ie.Navigate(URL)
ie.Visible=False
DO WHILE ie.busy
Wscript.Sleep 100
Loop
Data = ie.document.documentElement.innerHTML
Set objRegex = new RegExp
objRegex.Pattern = "\d{2}\.\d"
objRegex.Global = True
objRegex.IgnoreCase = True
Set Matches = objRegex.Execute(Data)
For Each Match in Matches
GetFirefoxMajorVersion = Match.Value
Next
ie.Quit
Set ie = Nothing
End Function
'***************************************************************************************
Here is another way to get FileVersion of Firefox.exe using Powershell and Vbscript
GetFileDetailsFirefox.vbs
Option Explicit
Dim MyCmd,Ws,Ret,ByPassPSFile,PSFile,PathFile,OutPut
Set Ws = CreateObject("wscript.Shell")
PathFile = Ws.ExpandEnvironmentStrings("%ProgramFiles%") & "\Mozilla Firefox\Firefox.exe"
OutPut = Ws.ExpandEnvironmentStrings("%Temp%") & "\firefox_version.txt"
PSFile = Left(Wscript.ScriptFullName,InstrRev(Wscript.ScriptFullName, ".")) & "ps1"
ByPassPSFile = "cmd /c PowerShell.exe -ExecutionPolicy bypass -noprofile -file "
MyCmd = "Get-ChildItem "& DblQuote(PathFile) &" | Get-ItemProperty | Select VersionInfo | Format-List > " & OutPut &""
Call WriteLog(MyCmd)
Ret = Ws.run(ByPassPSFile & PSFile,0,True)
ws.run DblQuote(OutPut)
'**********************************************************************************************
Sub WriteLog(strText)
Dim fs,ts,PSFile
Const ForWriting = 2
PSFile = Left(Wscript.ScriptFullName,InstrRev(Wscript.ScriptFullName, ".")) & "ps1"
Set fs = CreateObject("Scripting.FileSystemObject")
Set ts = fs.OpenTextFile(PSFile,ForWriting,True)
ts.WriteLine strText
ts.Close
End Sub
'**********************************************************************************************
Function DblQuote(Str)
DblQuote = Chr(34) & Str & Chr(34)
End Function
'***********************************************************************************************

VB Script help in writing event logs to excel

I have the below script to fetch the event logs from system and write to an excel. It is running fine on 'Windows 7', but on 'Windows Server 2003', it is taking 7-8 minutes to write the systems logs, and it writes the Application logs within seconds. However there are very few number of errors in the system logs.
Another problem is I am using MyDate = DateAdd("h", -8, Now()) in the script but it fetches logs for more than 12 hours ago. This time calculation is not functioning correctly.
Your help will be highly appreciated.
Here is the script:
Option Explicit
Dim objFSO, objFolder, objFile, objWMI, objItem, objItem1, objItem2 ' Objects
Dim strComputer, strFileName, strFileOpen, strFolder, strPath, oExcel, oWB, oSheet, oSheet1, oSheet2
Dim intEvent, intNumberID, intRecordNum, colLoggedEvents, colLoggedEvents2, colLoggedEvents3, MyDate, dtm, row, row1, row2, Query, ServerTime
MyDate = DateAdd("h", -8, Now())
'---------------------------------------------------------
On Error Resume Next
Set oExcel=CreateObject("Excel.Application")
oExcel.Visible=true
Set oWB=oExcel.Workbooks.Open ("D:\EventLogs2.xls")
Set oSheet=oWB.Worksheets.Add ( , oWB.WorkSheets(oWB.WorkSheets.Count))
Set oSheet1=oWB.Worksheets.Add ( , oWB.WorkSheets(oWB.WorkSheets.Count))
Set oSheet2=oWB.Worksheets.Add ( , oWB.WorkSheets(oWB.WorkSheets.Count))
oSheet.Name="Application"
oSheet1.Name="Security"
oSheet2.Name="System"
strComputer = "."
ServerTime = Now
intRecordNum = 0
row = 0
row1 = 0
row2 = 0
' ----------------------------------------------------------
' WMI Core Section
Set objWMI = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate,(Security)}!\\" _
& strComputer & "\root\cimv2")
Set colLoggedEvents = objWMI.ExecQuery _
("SELECT * FROM Win32_NTLogEvent where Logfile = 'Application' and " _
& "EventType = '1' and TimeWritten > '" & MyDate & "'")
Set colLoggedEvents2 = objWMI.ExecQuery _
("SELECT * FROM Win32_NTLogEvent where Logfile = 'Security' and " _
& "EventType = '1' and TimeWritten > '" & MyDate & "'")
Set colLoggedEvents3 = objWMI.ExecQuery _
("SELECT * FROM Win32_NTLogEvent where Logfile = 'System' and " _
& "EventType = '1' and TimeWritten > '" & MyDate & "'")
' ----------------------------------------------------------
' Next section loops through ID properties
For Each objItem in colLoggedEvents
If objItem.EventType=1 then
row = row+1
osheet.Cells(row,1).Value = ("Logfile: " & objItem.Logfile _
& " source " & objItem.SourceName)
osheet.Cells(row,2).Value = ("Message: " & objItem.Message)
osheet.Cells(row,3).Value = ("TimeGenerated: " & WMIDateStringToDate(objItem.TimeGenerated))
osheet.Cells(row,4).Value = ServerTime
End If
Next
For Each objItem1 in colLoggedEvents2
If objItem1.EventType=1 then
row1 = row1+1
osheet1.Cells(row1,1).Value = ("Logfile: " & objItem1.Logfile _
& " source " & objItem1.SourceName)
osheet1.Cells(row1,2).Value = ("Message: " & objItem1.Message)
osheet1.Cells(row1,3).Value = ("TimeGenerated: " & WMIDateStringToDate(objItem1.TimeGenerated))
osheet1.Cells(row1,4).Value = ServerTime
End If
Next
For Each objItem2 in colLoggedEvents3
If objItem2.EventType=1 then
row2 = row2+1
osheet2.Cells(row2,1).Value = ("Logfile: " & objItem2.Logfile _
& " source " & objItem2.SourceName)
osheet2.Cells(row2,2).Value = ("Message: " & objItem2.Message)
osheet2.Cells(row2,3).Value = ("TimeGenerated: " & WMIDateStringToDate(objItem2.TimeGenerated))
osheet2.Cells(row2,4).Value = ServerTime
intRecordNum = intRecordNum +1
End If
Next
Function WMIDateStringToDate(dtmDate)
WMIDateStringToDate = CDate(Mid(dtmDate, 5, 2) & "/" & _
Mid(dtmDate, 7, 2) & "/" & Left(dtmDate, 4) _
& " " & Mid (dtmDate, 9, 2) & ":" & Mid(dtmDate, 11, 2) & ":" & Mid(dtmDate,13, 2))
End Function
oWB.save
oWB.Application.Quit
WScript.Quit
Can't you just write to a CSV file?
Something like this:
Option Explicit
Dim objFSO, objFolder, objFile, objWMI, objItem, objItem1, objItem2 ' Objects
Dim strComputer, strFileName, strFileOpen, strFolder, strPath, oExcel, oWB, oSheet, oSheet1, oSheet2
Dim intEvent, intNumberID, intRecordNum, colLoggedEvents, colLoggedEvents2, colLoggedEvents3, MyDate, dtm, row, row1, row2, Query, ServerTime
MyDate = DateAdd("h", -8, Now())
'---------------------------------------------------------
On Error Resume Next
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.CreateTextFile("D:\EventLogs2.csv", True)
strComputer = "."
ServerTime = Now
intRecordNum = 0
row = 0
row1 = 0
row2 = 0
' ----------------------------------------------------------
' WMI Core Section
Set objWMI = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate,(Security)}!\\" _
& strComputer & "\root\cimv2")
Set colLoggedEvents = objWMI.ExecQuery _
("SELECT * FROM Win32_NTLogEvent where Logfile = 'Application' and " _
& "EventType = '1' and TimeWritten > '" & MyDate & "'")
Set colLoggedEvents2 = objWMI.ExecQuery _
("SELECT * FROM Win32_NTLogEvent where Logfile = 'Security' and " _
& "EventType = '1' and TimeWritten > '" & MyDate & "'")
Set colLoggedEvents3 = objWMI.ExecQuery _
("SELECT * FROM Win32_NTLogEvent where Logfile = 'System' and " _
& "EventType = '1' and TimeWritten > '" & MyDate & "'")
' ----------------------------------------------------------
' Next section loops through ID properties
For Each objItem in colLoggedEvents
If objItem.EventType=1 then
objFile.WriteLine("Logfile: " & objItem.Logfile & "," & " source " & objItem.SourceName & "," & _
"Message: " & objItem.Message & "," & _
"TimeGenerated: " & WMIDateStringToDate(objItem.TimeGenerated) & "," & _
ServerTime)
End If
Next
For Each objItem1 in colLoggedEvents2
If objItem1.EventType=1 then
objFile.WriteLine("Logfile: " & objItem1.Logfile & "," & " source " & objItem1.SourceName & "," & _
"Message: " & objItem1.Message & "," & _
"TimeGenerated: " & WMIDateStringToDate(objItem1.TimeGenerated) & "," & _
ServerTime)
End If
Next
For Each objItem2 in colLoggedEvents3
If objItem2.EventType=1 then
objFile.WriteLine("Logfile: " & objItem2.Logfile & "," & " source " & objItem2.SourceName & "," & _
"Message: " & objItem2.Message & "," & _
"TimeGenerated: " & WMIDateStringToDate(objItem2.TimeGenerated) & "," & _
ServerTime)
End If
Next
Function WMIDateStringToDate(dtmDate)
WMIDateStringToDate = CDate(Mid(dtmDate, 5, 2) & "/" & _
Mid(dtmDate, 7, 2) & "/" & Left(dtmDate, 4) _
& " " & Mid (dtmDate, 9, 2) & ":" & Mid(dtmDate, 11, 2) & ":" & Mid(dtmDate,13, 2))
End Function
objFile.Close
Set objFile = Nothing
Set objFSO = Nothing

attempting to run multiple scripts, have them all output to one file, and all use the same IP address

I have a couple questions and am hoping this is the correct place.
basically what i want to do is to be able to remotely get info about a domain computer.
i have 3 seperate scripts that give me 1( IP configuration, comp name ... ), 2 ( installed software ) and 3 ( mapped drives ).
the first two ask for the IP/computer name and the 3rd i have to input that into the script... i would like to only have to input the IP address once and have it work for all 3
secondly i would like the output file that this info is put into to be named like the installed software script does and then just have the other two scripts add ( ammend ) to the already created output.
I am super new to vbs so any help would be awesome
SCRIPT 1 ( gets IP configuration )
dim strComputer 'for computer name or IP
dim colAdapters 'collection of adapters
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.CreateTextFile("output.txt", True)
strComputer = ""
'open a dialog box asking for the computer name/IP
do
strComputer = inputbox( "Please enter a computername/IP, or . for local computer", "Input" )
Loop until strComputer <> "" 'run until a name/IP is entered
Set objWMIService = GetObject ("winmgmts:" & "!\\" & strComputer & "\root\cimv2") 'open the WMI service on the remote PC
Set colAdapters = objWMIService.ExecQuery ("Select * from Win32_NetworkAdapterConfiguration Where IPEnabled = True")
'go through the list of adapters and gather data
For Each objAdapter in colAdapters
objFile.Writeline "Host name: " & objAdapter.DNSHostName
objFile.Writeline "DNS domain: " & objAdapter.DNSDomain
objFile.Writeline "DNS suffix search list: " & objAdapter.DNSDomainSuffixSearchOrder
objFile.Writeline "Description: " & objAdapter.Description
objFile.Writeline "Physical address: " & objAdapter.MACAddress
objFile.Writeline "DHCP enabled: " & objAdapter.DHCPEnabled
If Not IsNull(objAdapter.IPAddress) Then
For i = LBound(objAdapter.IPAddress) To UBound(objAdapter.IPAddress)
objFile.Writeline "IP address: " & objAdapter.IPAddress(i)
Next
End If
If Not IsNull(objAdapter.IPSubnet) Then
For i = LBound(objAdapter.IPSubnet) To UBound(objAdapter.IPSubnet)
objFile.Writeline "Subnet: " & objAdapter.IPSubnet(i)
Next
End If
If Not IsNull(objAdapter.DefaultIPGateway) Then
For i = LBound(objAdapter.DefaultIPGateway) To UBound(objAdapter.DefaultIPGateway)
objFile.Writeline "Default gateway: " & objAdapter.DefaultIPGateway(i)
Next
End If
objFile.Writeline "DHCP server: " & objAdapter.DHCPServer
If Not IsNull(objAdapter.DNSServerSearchOrder) Then
For i = LBound(objAdapter.DNSServerSearchOrder) To UBound(objAdapter.DNSServerSearchOrder)
objFile.Writeline "DNS server: " & objAdapter.DNSServerSearchOrder(i)
Next
End If
objFile.Writeline "Primary WINS server: " & objAdapter.WINSPrimaryServer
objFile.Writeline "Secondary WINS server: " & objAdapter.WINSSecondaryServer
objFile.Writeline "Lease obtained: " & objAdapter.DHCPLeaseObtained
objFile.Writeline "Lease expires: " & objAdapter.DHCPLeaseExpires
Next
SCRIPT 2 ( gets installed software )
Option Explicit
Dim sTitle
sTitle = "InstalledPrograms.vbs by Bill James"
Dim StrComputer
strComputer = InputBox("Enter I.P. or name of computer to check for " & _
"installed software (leave blank to check " & _
"local system)." & vbcrlf & vbcrlf & "Remote " & _
"checking only from NT type OS to NT type OS " & _
"with same Admin level UID & PW", sTitle)
If IsEmpty(strComputer) Then WScript.Quit
strComputer = Trim(strComputer)
If strComputer = "" Then strComputer = "."
'Wscript.Echo GetAddRemove(strComputer)
Dim sCompName : sCompName = GetProbedID(StrComputer)
Dim sFileName
sFileName = sCompName & "_" & GetDTFileName() & "_Software.txt"
Dim s : s = GetAddRemove(strComputer)
If WriteFile(s, sFileName) Then
'optional prompt for display
If MsgBox("Finished processing. Results saved to " & sFileName & _
vbcrlf & vbcrlf & "Do you want to view the results now?", _
4 + 32, sTitle) = 6 Then
WScript.CreateObject("WScript.Shell").Run sFileName, 9
End If
End If
Function GetAddRemove(sComp)
'Function credit to Torgeir Bakken
Dim cnt, oReg, sBaseKey, iRC, aSubKeys
Const HKLM = &H80000002 'HKEY_LOCAL_MACHINE
Set oReg = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & _
sComp & "/root/default:StdRegProv")
sBaseKey = "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\"
iRC = oReg.EnumKey(HKLM, sBaseKey, aSubKeys)
Dim sKey, sValue, sTmp, sVersion, sDateValue, sYr, sMth, sDay
For Each sKey In aSubKeys
iRC = oReg.GetStringValue(HKLM, sBaseKey & sKey, "DisplayName", sValue)
If iRC <> 0 Then
oReg.GetStringValue HKLM, sBaseKey & sKey, "QuietDisplayName", sValue
End If
If sValue <> "" Then
iRC = oReg.GetStringValue(HKLM, sBaseKey & sKey, _
"DisplayVersion", sVersion)
If sVersion <> "" Then
sValue = sValue & vbTab & "Ver: " & sVersion
Else
sValue = sValue & vbTab
End If
iRC = oReg.GetStringValue(HKLM, sBaseKey & sKey, _
"InstallDate", sDateValue)
If sDateValue <> "" Then
sYr = Left(sDateValue, 4)
sMth = Mid(sDateValue, 5, 2)
sDay = Right(sDateValue, 2)
'some Registry entries have improper date format
On Error Resume Next
sDateValue = DateSerial(sYr, sMth, sDay)
On Error GoTo 0
If sdateValue <> "" Then
sValue = sValue & vbTab & "Installed: " & sDateValue
End If
End If
sTmp = sTmp & sValue & vbcrlf
cnt = cnt + 1
End If
Next
sTmp = BubbleSort(sTmp)
GetAddRemove = "INSTALLED SOFTWARE (" & cnt & ") - " & sCompName & _
" - " & Now() & vbcrlf & vbcrlf & sTmp
End Function
Function BubbleSort(sTmp)
'cheapo bubble sort
Dim aTmp, i, j, temp
aTmp = Split(sTmp, vbcrlf)
For i = UBound(aTmp) - 1 To 0 Step -1
For j = 0 to i - 1
If LCase(aTmp(j)) > LCase(aTmp(j+1)) Then
temp = aTmp(j + 1)
aTmp(j + 1) = aTmp(j)
aTmp(j) = temp
End if
Next
Next
BubbleSort = Join(aTmp, vbcrlf)
End Function
Function GetProbedID(sComp)
Dim objWMIService, colItems, objItem
Set objWMIService = GetObject("winmgmts:\\" & sComp & "\root\cimv2")
Set colItems = objWMIService.ExecQuery("Select SystemName from " & _
"Win32_NetworkAdapter",,48)
For Each objItem in colItems
GetProbedID = objItem.SystemName
Next
End Function
Function GetDTFileName()
dim sNow, sMth, sDay, sYr, sHr, sMin, sSec
sNow = Now
sMth = Right("0" & Month(sNow), 2)
sDay = Right("0" & Day(sNow), 2)
sYr = Right("00" & Year(sNow), 4)
sHr = Right("0" & Hour(sNow), 2)
sMin = Right("0" & Minute(sNow), 2)
sSec = Right("0" & Second(sNow), 2)
GetDTFileName = sMth & sDay & sYr & "_" & sHr & sMin & sSec
End Function
Function WriteFile(sData, sFileName)
Dim fso, OutFile, bWrite
bWrite = True
Set fso = CreateObject("Scripting.FileSystemObject")
On Error Resume Next
Set OutFile = fso.OpenTextFile(sFileName, 2, True)
'Possibly need a prompt to close the file and one recursion attempt.
If Err = 70 Then
Wscript.Echo "Could not write to file " & sFileName & ", results " & _
"not saved." & vbcrlf & vbcrlf & "This is probably " & _
"because the file is already open."
bWrite = False
ElseIf Err Then
WScript.Echo err & vbcrlf & err.description
bWrite = False
End If
On Error GoTo 0
If bWrite Then
OutFile.WriteLine(sData)
OutFile.Close
End If
Set fso = Nothing
Set OutFile = Nothing
WriteFile = bWrite
End Function
SCRIPT 3 ( gets mapped drives )
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.CreateTextFile("mappedoutput.txt", True)
' List Mapped Network Drives
On Error Resume Next
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colItems = objWMIService.ExecQuery("Select * from Win32_MappedLogicalDisk")
For Each objItem in colItems
objFile.Writeline "Compressed: " & objItem.Compressed
objFile.Writeline "Description: " & objItem.Description
objFile.Writeline "Device ID: " & objItem.DeviceID
objFile.Writeline "File System: " & objItem.FileSystem
objFile.Writeline "Free Space: " & objItem.FreeSpace
objFile.Writeline "Maximum Component Length: " & objItem.MaximumComponentLength
objFile.Writeline "Name: " & objItem.Name
objFile.Writeline "Provider Name: " & objItem.ProviderName
objFile.Writeline "Session ID: " & objItem.SessionID
objFile.Writeline "Size: " & objItem.Size
objFile.Writeline "Supports Disk Quotas: " & objItem.SupportsDiskQuotas
objFile.Writeline "Supports File-Based Compression: " & _
objItem.SupportsFileBasedCompression
objFile.Writeline "Volume Name: " & objItem.VolumeName
objFile.Writeline "Volume Serial Number: " & objItem.VolumeSerialNumber
objFile.Writeline
Next
Again thank you
Can you put all the three scripts as 1 single script? In that case, you will need to input the IP address only once.
Or else write another script which will ask for the IP address and call these scripts by using cscript and passing the IPaddress to them as a parameter. Try this code for that:
strcomputer = inputbox("Enter the IP address")
set obj1 = createobject("wscript.shell")
set obj2 = createobject("wscript.shell")
set obj3 = createobject("wscript.shell")
pgm1 = "cscript script1.vbs " & strcomputer
pgm2 = "cscript script2.vbs " & strcomputer
pgm3 = "cscript script3.vbs " & strcomputer
obj1.run pgm1,3,true
obj2.run pgm2,3,true
obj3.run pgm3,3,true
set obj1 = nothing
set obj2 = nothing
set obj3 = nothing
In above code, script1.vbs, script2.vbs, script3.vbs are your 3 scripts and you are executing them one by one using a new script.
In script1.vbs, add this line of code :
strcomputer = wscript.Arguments.item(0)
It will store the 1rst argument that you have passed from your new script to script1.vbs, into the variable 'strcomputer'(in your case, the IP address).
Similarly, in both script2.vbs and script3.vbs also, add the statement
strcomputer = wscript.Arguments.item(0)
Regarding your output file, I am not sure what you are asking for. Maybe this can help:
Use the below to write to a file (overwrites if data is already present):
Set fso1 = CreateObject("Scripting.FileSystemObject" )
Set file1 = fso1.OpenTextFile("C:\New\textfile1.txt",2,true)
Use the below to add data or append to a file (does NOT overwrite):
Set fso1 = CreateObject("Scripting.FileSystemObject" )
Set file1 = fso1.OpenTextFile("C:\New\textfile1.txt",8,true)
Use the below to read from a file:
Set fso1 = CreateObject("Scripting.FileSystemObject" )
Set file1 = fso1.OpenTextFile("C:\New\textfile1.txt",1,true)

Runtime error 3704

In my vb6 I am getting error 3704 operation is not allowed when object is closed.
I have search stackoverflow for similar problem but I think I'm missing something. I need to update every row in vfp based from recordset rs1 Here my code:
Option Explicit
Dim cn As New ADODB.Connection
Dim cn1 As New ADODB.Connection
Private Sub trns_Click()
Set cn = New ADODB.Connection
Set cn1 = New ADODB.Connection
cn.ConnectionString = MDI1.txtcn.Text
cn.Open
cn1.ConnectionString = "Provider=VFPOLEDB;Data Source=\\host1\software\MIL\company0"
cn1.Open
rs1.Open "Select * from trans", cn, adOpenStatic, adLockPessimistic
Do While Not rs2.EOF
rs2.Open "update transac set no_ot_1_5 = " & rs1.Fields("ovt1") & ", no_ot_2_0 = " & rs1.Fields("ovt2") & ", no_ot_3_0" _
& "= " & rs1.Fields("ovt3") & ",Meal_allw = " & rs1.Fields("meal_allow") & ",on_duty = " & rs1.Fields("cnt") & ",no_d_local = " & rs1.Fields("local") & ",no_d_sick" _
& "= " & rs1.Fields("sick") & ",no_d_abs = " & rs1.Fields("absence") & ",no_d_spc = " & rs1.Fields("special") & ",Revenue02" _
& "= " & rs1.Fields("refund") & ",Revenue05 = " & rs1.Fields("prepay") & ",Deduct05 = " & rs1.Fields("prepay") & ",Revenue01 = " & rs1.Fields("comm") & "where code = '" & rs1.Fields("emp_code") & "' and transac.date = CTOD('" & trans.txtend2 & "')", cn1, adOpenDynamic, adLockPessimistic
If Not rs2.EOF Then
rs2.MoveNext
End If
Loop
rs2.close
Update query doesn't return recordset, hence your rs2 is not opened.
You perform your loop on the wrong recordeset : I replaced the some of the rs2 with rs1 in your code.
Do While Not rs1.EOF
rs2.Open "update transac set no_ot_1_5 = " & rs1.Fields("ovt1") & ", no_ot_2_0 = " & rs1.Fields("ovt2") & ", no_ot_3_0" _
& "= " & rs1.Fields("ovt3") & ",Meal_allw = " & rs1.Fields("meal_allow") & ",on_duty = " & rs1.Fields("cnt") & ",no_d_local = " & rs1.Fields("local") & ",no_d_sick" _
& "= " & rs1.Fields("sick") & ",no_d_abs = " & rs1.Fields("absence") & ",no_d_spc = " & rs1.Fields("special") & ",Revenue02" _
& "= " & rs1.Fields("refund") & ",Revenue05 = " & rs1.Fields("prepay") & ",Deduct05 = " & rs1.Fields("prepay") & ",Revenue01 = " & rs1.Fields("comm") & "where code = '" & rs1.Fields("emp_code") & "' and transac.date = CTOD('" & trans.txtend2 & "')", cn1, adOpenDynamic, adLockPessimistic
If Not rs1.EOF Then
rs1.MoveNext
End If
Loop
rs1.close
You dont need to create a recordset to execute an update, insert or delete on the database. Just use the statement cn1.Execute YourSqlStatement where YourSqlStatement is the string you are passing on the rs2.Open instruction. The Execute method on the connection optionally accepts a byRef variable where you can get the number of records affected.
Example:
Dim nRecords As Integer
cn1.Execute "Update Table Set Field = Value Where AnotherField = SomeValue ", nRecords
MsgBox "Total Updated Records: " & Format(nRecords,"0")
try to open your rs2 before using if in the do while statement., or do it like this
rs2.open " blah blah blah "
Do Until rs2.eof
For Each fld In rs2.field
value_holder = fld.value
Next
rs2.movenext
Loop

Deduplication and filtering of Add/Remove Programs list (VBScript)

This script works and tells and me what is installed in Program files.
Two problems
Duplicate lines
i.e
AVG 2011 Ver: 10.0.1204
AVG 2011 Ver: 10.0.1204 Installed: 27/01/2011
and
I don't want to include lines that have key words "Update","Hotfix","Java" can any VB gurus out there help with what extra is needed in this script?
Option Explicit
Dim sTitle
sTitle = "Installed Programs on your PC -"
Dim StrComputer
strComputer = Trim(strComputer)
If strComputer = "" Then strComputer = "."
'Wscript.Echo GetAddRemove(strComputer)
Dim sCompName : sCompName = GetProbedID(StrComputer)
Dim sFileName
sFileName = sCompName & "_" & GetDTFileName() & "_Software.txt"
Dim s : s = GetAddRemove(strComputer)
If WriteFile(s, sFileName) Then
'optional prompt for display
If MsgBox("Finished processing. Results saved to " & sFileName & _
vbcrlf & vbcrlf & "Do you want to view the results now?", _
4 + 32, sTitle) = 6 Then
WScript.CreateObject("WScript.Shell").Run sFileName, 9
End If
End If
Function GetAddRemove(sComp)
'Function credit to Torgeir Bakken
Dim cnt, oReg, sBaseKey, iRC, aSubKeys
Const HKLM = &H80000002 'HKEY_LOCAL_MACHINE
Set oReg = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & _
sComp & "/root/default:StdRegProv")
sBaseKey = "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\"
iRC = oReg.EnumKey(HKLM, sBaseKey, aSubKeys)
Dim sKey, sValue, sTmp, sVersion, sDateValue, sYr, sMth, sDay
For Each sKey In aSubKeys
iRC = oReg.GetStringValue(HKLM, sBaseKey & sKey, "DisplayName", sValue)
If iRC <> 0 Then
oReg.GetStringValue HKLM, sBaseKey & sKey, "QuietDisplayName", sValue
End If
If sValue <> "" Then
iRC = oReg.GetStringValue(HKLM, sBaseKey & sKey, _
"DisplayVersion", sVersion)
If sVersion <> "" Then
sValue = sValue & vbTab & "Ver: " & sVersion
Else
sValue = sValue & vbTab
End If
iRC = oReg.GetStringValue(HKLM, sBaseKey & sKey, _
"InstallDate", sDateValue)
If sDateValue <> "" Then
sYr = Left(sDateValue, 4)
sMth = Mid(sDateValue, 5, 2)
sDay = Right(sDateValue, 2)
'some Registry entries have improper date format
On Error Resume Next
sDateValue = DateSerial(sYr, sMth, sDay)
On Error GoTo 0
If sdateValue <> "" Then
sValue = sValue & vbTab & "Installed: " & sDateValue
End If
End If
sTmp = sTmp & sValue & vbcrlf
cnt = cnt + 1
End If
Next
sTmp = BubbleSort(sTmp)
GetAddRemove = "INSTALLED SOFTWARE (" & cnt & ") - " & sCompName & _
" - " & Now() & vbcrlf & vbcrlf & sTmp
End Function
Function BubbleSort(sTmp)
'cheapo bubble sort
Dim aTmp, i, j, temp
aTmp = Split(sTmp, vbcrlf)
For i = UBound(aTmp) - 1 To 0 Step -1
For j = 0 to i - 1
If LCase(aTmp(j)) > LCase(aTmp(j+1)) Then
temp = aTmp(j + 1)
aTmp(j + 1) = aTmp(j)
aTmp(j) = temp
End if
Next
Next
BubbleSort = Join(aTmp, vbcrlf)
End Function
Function GetProbedID(sComp)
Dim objWMIService, colItems, objItem
Set objWMIService = GetObject("winmgmts:\\" & sComp & "\root\cimv2")
Set colItems = objWMIService.ExecQuery("Select SystemName from " & _
"Win32_NetworkAdapter",,48)
For Each objItem in colItems
GetProbedID = objItem.SystemName
Next
End Function
Function GetDTFileName()
dim sNow, sMth, sDay, sYr, sHr, sMin, sSec
sNow = Now
sMth = Right("0" & Month(sNow), 2)
sDay = Right("0" & Day(sNow), 2)
sYr = Right("00" & Year(sNow), 4)
sHr = Right("0" & Hour(sNow), 2)
sMin = Right("0" & Minute(sNow), 2)
sSec = Right("0" & Second(sNow), 2)
GetDTFileName = sMth & sDay & sYr & "_" & sHr & sMin & sSec
End Function
Function WriteFile(sData, sFileName)
Dim fso, OutFile, bWrite
bWrite = True
Set fso = CreateObject("Scripting.FileSystemObject")
On Error Resume Next
Set OutFile = fso.OpenTextFile(sFileName, 2, True)
'Possibly need a prompt to close the file and one recursion attempt.
If Err = 70 Then
Wscript.Echo "Could not write to file " & sFileName & ", results " & _
"not saved." & vbcrlf & vbcrlf & "This is probably " & _
"because the file is already open."
bWrite = False
ElseIf Err Then
WScript.Echo err & vbcrlf & err.description
bWrite = False
End If
On Error GoTo 0
If bWrite Then
OutFile.WriteLine(sData)
OutFile.Close
End If
Set fso = Nothing
Set OutFile = Nothing
WriteFile = bWrite
End Function
#icecurtain: The second part of your question can be solved using InStr as suggested by #Oliver, rewritten to suit your script it would look like --
If sValue <> "" _
AND (InStr(1, sValue, "Hotfix", 1)) = 0 _
AND (InStr(1, sValue, "Update", 1)) = 0 _
AND (InStr(1, sValue, "Java", 1)) = 0) Then
The first part wouldn't be that tricky either except for the fact that you include a version and installation date if found (which some of the duplicates will only include in part or not at all). If the extra bits of data wasn't included, you could loop through all the lines and add them into a Scripting.Dictory object with a .Exists check to prevent a duplicate from being added.
Ok, even if i'm not a jedi master (or have no self-respect ;-)), this could help you:
If InStr(1, sValue, "hotfix", vbTextCompare) = 0 Then
Print "This is NOT a hotfix"
End If
For further informations just take a look at the MSDN page for InStr().
I don't think hardcoded string checks are the way to go, a uninstall entry is a update if any of these are true:
It has a dword value named SystemComponent that is <> 0
A string value named ParentKeyName
The registry sub key starts with "KB" or "Q" + 6 numbers (KB######,Q######)

Resources