I would like to analyze the event log of a special windows application (Windows 7 Enterprise, 64Bit).
I need a special event which is logged some seconds ago.
Here is my VBScript code, which produces a completely wrong result (wrong number of events):
strComputer = "." ' Dieser Computer
' Retrieving Specific Events from an Event Log
Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\" & strComputer & "\root\cimv2")
Const CONVERT_TO_LOCAL_TIME = True
Set dtmStartDate = CreateObject("WbemScripting.SWbemDateTime")
Set dtmEndDate = CreateObject("WbemScripting.SWbemDateTime")
dtmStartDate.SetVarDate dateadd("s", -10, now()) ' CONVERT_TO_LOCAL_TIME
dtmEndDate.SetVarDate now() ' CONVERT_TO_LOCAL_TIME
dim var_wql
var_wql = "SELECT * FROM Win32_NTLogEvent WHERE Logfile = '< ... >' AND SourceName = '< ... >' AND EventCode = '< ... >' AND (TimeWritten >= '" & dtmStartDate & "') AND (TimeWritten < '" & dtmEndDate & "')"
Set colLoggedEvents = objWMIService.ExecQuery(var_wql)
...
The number of rows (anzahl = colLoggedEvents.count) must be 0 or 1, anything else is impossible.
What is wrong with the wql statement? I would like to check the last seconds in the past (from now).
Thanks.
Tommy
Syntax error. If I change the objWMIService line to this, it works for me.
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate,authenticationLevel=pktPrivacy}!\\" & strComputer & "\root\cimv2")
Updated to grab ALL event logs created in the last 10 secs and write to log file.
On Error Resume Next
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate,authenticationLevel=pktPrivacy}!\\.\root\cimv2")
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set WshShell = WScript.CreateObject("WScript.Shell")
strSystemDrive = WshShell.ExpandEnvironmentStrings("%SystemDrive%")
Const CONVERT_TO_LOCAL_TIME = True
Set dtmStartDate = CreateObject("WbemScripting.SWbemDateTime")
Set dtmEndDate = CreateObject("WbemScripting.SWbemDateTime")
dtmStartDate.SetVarDate dateadd("s", -10, now()) ' CONVERT_TO_LOCAL_TIME
dtmEndDate.SetVarDate now() ' CONVERT_TO_LOCAL_TIME
var_wql = "SELECT * FROM Win32_NTLogEvent WHERE (TimeWritten >= '" & dtmStartDate & "') AND (TimeWritten < '" & dtmEndDate & "')"
Set LogFile = objFSO.CreateTextFile(strSystemDrive & "\Temp\EvtLog.txt", True)
Set colLoggedEvents = objWMIService.ExecQuery(var_wql)
For Each objEvent in colLoggedEvents
LogFile.WriteLine "Computer Name : " & objEvent.ComputerName
LogFile.WriteLine "Logfile : " & objEvent.Logfile
LogFile.WriteLine "Type : " & objEvent.Type
LogFile.WriteLine "User : " & objEvent.User
LogFile.WriteLine "Category : " & objEvent.Category
LogFile.WriteLine "Category String : " & objEvent.CategoryString
If IsArray(objEvent.Data) Then
For i = 0 To UBound(objEvent.Data)
strData = strData & objEvent.Data(i) & ","
Next
LogFile.WriteLine "Data : " & strData
Else
LogFile.WriteLine "Data : " & objEvent.Data
End If
LogFile.WriteLine "Event Code : " & objEvent.EventCode
LogFile.WriteLine "Event Identifier : " & objEvent.EventIdentifier
LogFile.WriteLine "Message : " & objEvent.Message
LogFile.WriteLine "Record Number : " & objEvent.RecordNumber
LogFile.WriteLine "Source Name : " & objEvent.SourceName
LogFile.WriteLine "Time Generated : " & objEvent.TimeGenerated
LogFile.WriteLine "Time Written : " & objEvent.TimeWritten
If IsArray(objEvent.InsertionStrings) Then
For i = 0 To UBound(objEvent.InsertionStrings)
strInsert = strInsert & objEvent.InsertionStrings(i) & ","
Next
LogFile.WriteLine "Insertion Strings: " & strInsert
Else
LogFile.WriteLine "Insertion Strings: " & objEvent.InsertionStrings
End If
LogFile.WriteLine "----------------------------------------------------------------------------------------------------------"
Next
Output sample (Not all fields used for every event) -
----------------------------------------------------------------------------------------------------------
Computer Name : Randy-PC
Logfile : Application
Type : Information
User :
Category : 0
Category String :
Data :
Event Code : 9019
Event Identifier : 1073750843
Message : The Desktop Window Manager was unable to start because the desktop composition setting is disabled
Record Number : 37395
Source Name : Desktop Window Manager
Time Generated : 20160903031728.000000-000
Time Written : 20160903031728.000000-000
Insertion Strings:
----------------------------------------------------------------------------------------------------------
Related
This code sample is part of a vbscript script that
is making HTTP POST requests for sending SMS through an API. For each SMS, I need a unique random ID. A description of the functions:
WriteLog (Create log files)
MoveLogFiles (Archiving old log files)
CreateGUID (Generate GUIDs for each SMS)
The problem here is when I write to the log file. I tried apache benchmark to stress test my script. In the log file, the smsID is not stored correctly. It is supposed to be unique for each http request. Instead I see the same ID written in many entries in the log file. How can I protect the variable so that it writes the appropriate value in the log file when the script is called multiple times?
Private smsID
smsID = CreateGUID(12)
'HTTP Request & Response
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
WriteLog smsID, "[SMS ID:" & smsID & "] Starting HTTP Request..."
WriteLog smsID, "[SMS ID:" & smsID & "] JSON to be sent: " & JSONStringNoPIN
WriteLog smsID, "[SMS ID:" & smsID & "] Sending HTTP Request..."
ASPPostJSON(smsID)
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
set JSONString = Nothing
set JSONStringNoPIN = Nothing
set JSONRequest = Nothing
logFilesDic.RemoveAll
Set logFilesDic = Nothing
WriteLog smsID, "[SMS ID:" & smsID & "] Finished..." & vbCrLf
Set smsID=Nothing
Function WriteLog(ByVal smsID_, ByVal psMessage)
Dim fs: Set fs = Server.CreateObject("Scripting.FileSystemObject")
' Check if the log file and folder exists
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
dim f, logSize, logDic
On Error Resume Next
Set f = fs.GetFile(logFile)
Set logDic = CreateObject("Scripting.Dictionary")
'logDic.Add "1", Now() & vbTab & "[SMS ID:" & smsID_ & "] Opening Log file: " & logFile
If Err.Number <> 0 Then
logDic.Add "1", Now() & vbTab & "[SMS ID:" & smsID_ & "] An error occured while opening the log file. Error #" & Err.Number & ": " & Err.Description
If Err.Number = 53 And Not fs.FileExists(logFile) Then
if Not fs.FolderExists Then
fs.CreateFolder logDirectory
End if
if Not fs.FileExists(logFile) Then
fs.CreateTextFile logFile
logDic.Add "2", Now() & vbTab & "[SMS ID:" & smsID_ & "] Log file was created: " & logFile
End if
Set f = fs.GetFile(logFile)
End if
End if
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Check if the log size exceeds the log size limit
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
logSize = f.Size
if logSize >= logMaxSize Then
logDic.Add "3", Now() & vbTab & "[SMS ID:" & smsID_ & "] Log file is exceeding the maximum file size allowed:" & logMaxSize & " Bytes. Archiving the current log file: " & logFile
MoveLogFiles()
fs.CreateTextFile logFile
logDic.Add "4", Now() & vbTab & "[SMS ID:" & smsID_ & "] Log file was archived: " & logTemp
End if
set f=nothing
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Write to the log file
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Application.Lock
dim log, logDicItems
Set log = fs.OpenTextFile(logFile, 8, True) '1=ForReading, 2=ForWriting, 8=ForAppending
If logDic.Exists("1") Then log.WriteLine logDic.Item("1")
If logDic.Exists("2") Then log.WriteLine logDic.Item("2")
If logDic.Exists("3") Then log.WriteLine logDic.Item("3")
If logDic.Exists("4") Then log.WriteLine logDic.Item("4")
log.WriteLine Now() & vbTab & psMessage
log.Close
Application.UnLock
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Set log = Nothing
fs.Close()
Set fs = Nothing
logDic.RemoveAll
Set logDic = Nothing
WriteLog = True
End Function
Function MoveLogFiles()
Dim fs: Set fs = Server.CreateObject("Scripting.FileSystemObject")
For i = logMaxArchives To 1 Step -1
if fs.FileExists(logFile & "." & CStr(i)) Then
if i = logMaxArchives Then
fs.DeleteFile logDirectory & logFilesDic.Item(logMaxArchives)
Else
fs.MoveFile logDirectory & logFilesDic.Item(i), logDirectory & logFilesDic.Item(i+1)
End if
End if
Next
fs.MoveFile logDirectory & logFilesDic.Item(0), logDirectory & logFilesDic.Item(1)
fs.Close()
End Function
' Generate unique identifier for SMS
Function CreateGUID(tmpLength)
Application.Lock
if tmpLength >= 64 or tmpLength < 0 Then
WriteLog "Error when generating SMS ID. Maximum length of characters allowed: 64. Value given: " & tmpLength
Elseif tmpLength < 4 Then
WriteLog "Error when generating SMS ID. Minimum length of characters allowed: 4. Value given: " & tmpLength
Else
Randomize Timer
Dim tmpCounter,tmpGUID
Const strValid = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
For tmpCounter = 1 To tmpLength
tmpGUID = tmpGUID & Mid(strValid, Int(Rnd(1) * Len(strValid)) + 1, 1)
Next
CreateGUID = tmpGUID
End if
Application.UnLock
End Function
Eventually the problem was caused by the Randomize Timer. Instead I used this:
Function CreateGUID()
Dim TypeLib: Set TypeLib = CreateObject("Scriptlet.TypeLib")
CreateGUID = TypeLib.Guid
CreateGUID = Left(CreateGUID, Len(CreateGUID)-3)
CreateGUID = Mid(CreateGUID,2)
Response.Write CreateGUID
End Function
I want to get a unique id of a mouse provided that every mouse brand is the same in a laboratory.
I have tried using WMIC to get device attributes. My VBS script is this:
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2")
Set colItems = objWMIService.ExecQuery( _
"SELECT * FROM Win32_PointingDevice",,48)
Wscript.Echo "DeviceID: " & objItem.DeviceID
I have tried generating this script with different mouse brand and it outputs a unique device id. But when I use the same model/brand of mouse, the same device id is generated. Please help me find a unique data to be used to identify every mouse in a laboratory.
I think Thangadurai is right with his comment do your original question... However, you could try to find desired mouse id running next code snippets.
The simpliest solution with wmic:
wmic path Win32_PointingDevice get * /FORMAT:Textvaluelist.xsl
About the same output with vbScript: use cscript 28273913.vbs if saved as 28273913.vbs.
' VB Script Document
option explicit
' NameSpace: \root\CIMV2 Class : Win32_PointingDevice
' D:\VB_scripts_help\Scriptomatic
'
On Error GOTO 0
Dim arrComputers, strComputer, objWMIService, colItems, objItem
Dim strPowerManagementCapabilities
arrComputers = Array(".")
WScript.Echo "NameSpace: \root\CIMV2 Class : Win32_PointingDevice"
For Each strComputer In arrComputers
WScript.Echo "..."
WScript.Echo "=========================================="
WScript.Echo "Computer: " & strComputer
WScript.Echo "=========================================="
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2")
Set colItems = objWMIService.ExecQuery( _
"SELECT * FROM Win32_PointingDevice", "WQL", _
wbemFlagReturnImmediately + wbemFlagForwardOnly)
For Each objItem In colItems
WScript.Echo "Availability: " & objItem.Availability
WScript.Echo "Caption: " & objItem.Caption
WScript.Echo "ConfigManagerErrorCode: " & objItem.ConfigManagerErrorCode
WScript.Echo "ConfigManagerUserConfig: " & objItem.ConfigManagerUserConfig
WScript.Echo "CreationClassName: " & objItem.CreationClassName
WScript.Echo "Description: " & objItem.Description
WScript.Echo "DeviceID: " & objItem.DeviceID
WScript.Echo "DeviceInterface: " & objItem.DeviceInterface
WScript.Echo "DoubleSpeedThreshold: " & objItem.DoubleSpeedThreshold
WScript.Echo "ErrorCleared: " & objItem.ErrorCleared
WScript.Echo "ErrorDescription: " & objItem.ErrorDescription
WScript.Echo "Handedness: " & objItem.Handedness
WScript.Echo "HardwareType: " & objItem.HardwareType
WScript.Echo "InfFileName: " & objItem.InfFileName
WScript.Echo "InfSection: " & objItem.InfSection
WScript.Echo "InstallDate: " & WMIDateStringToDate(objItem.InstallDate)
WScript.Echo "IsLocked: " & objItem.IsLocked
WScript.Echo "LastErrorCode: " & objItem.LastErrorCode
WScript.Echo "Manufacturer: " & objItem.Manufacturer
WScript.Echo "Name: " & objItem.Name
WScript.Echo "NumberOfButtons: " & objItem.NumberOfButtons
WScript.Echo "PNPDeviceID: " & objItem.PNPDeviceID
WScript.Echo "PointingType: " & objItem.PointingType
If Isnull( objItem.PowerManagementCapabilities) Then
strPowerManagementCapabilities=""
Else
strPowerManagementCapabilities=Join(objItem.PowerManagementCapabilities, ",")
End If
WScript.Echo "PowerManagementCapabilities: " & strPowerManagementCapabilities
WScript.Echo "PowerManagementSupported: " & objItem.PowerManagementSupported
WScript.Echo "QuadSpeedThreshold: " & objItem.QuadSpeedThreshold
WScript.Echo "Resolution: " & objItem.Resolution
WScript.Echo "SampleRate: " & objItem.SampleRate
WScript.Echo "Status: " & objItem.Status
WScript.Echo "StatusInfo: " & objItem.StatusInfo
WScript.Echo "Synch: " & objItem.Synch
WScript.Echo "SystemCreationClassName: " & objItem.SystemCreationClassName
WScript.Echo "SystemName: " & objItem.SystemName
WScript.Echo "."
Next
Next
Function WMIDateStringToDate(dtmDate)
WMIDateStringToDate = ( Left(dtmDate, 4) & "/" & _
Mid(dtmDate, 5, 2) & "/" & Mid(dtmDate, 7, 2) _
& " " & Mid (dtmDate, 9, 2) & ":" & Mid(dtmDate, 11, 2) & ":" & Mid(dtmDate,13, 2))
End Function
Const wbemFlagReturnImmediately = &h10
Const wbemFlagForwardOnly = &h20
More complex than previous wmic example providing possibility to run it against more computers in one step. Note the arrComputers = Array(".") line. Here "." means This computer and could be rewritten by a list of computer names or IP addresses e.g.
arrComputers = Array _
( "computer_1_name" _
, "computer_2_IP" _
, "computer_3_name" _
)
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)
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
I have written a VBScript to enumerate events from the event log on a particular day.
The first query select from the NT event log events between todays date and yesterdays date,
Set colEvents = objWMIService.ExecQuery _
("Select * from Win32_NTLogEvent Where TimeWritten >= '" _
& dtmStartDate & "' and TimeWritten < '" & dtmEndDate & "'")
Then from the query above i want to extract event id's from a log file.
For Each objEvent in colEvents
If objEvent.Eventcode = EventNu And (objEvent.LogFile = EventLog) Then
I have placed the following into the script and it works, however I want to use arguments instead via command line (i.e. EventLogCheck.vbs EventNumber LogFile )but if i use the arguments secion of the script no items are returned. This is driving me nuts. The full script below uses variables, i have commented out the arguments section, but you can uncomment them and play around with it. What am i doing wrong? Thanks for any help!
Const CONVERT_TO_LOCAL_TIME = True
Dim EventLog
EventNu = 18
EventLog = "System"
'Input from the command line
'If Wscript.Arguments.Count <= 1 Then
' Wscript.Echo "Usage: EventLogCheck.vbs EventNumber LogFile"
' Wscript.Quit
'End If
'EventNu = WScript.Arguments.Item(0)
'EventLog = WScript.Arguments.Item(1)
'For Each Computer In Wscript.Arguments
Set dtmStartDate = CreateObject("WbemScripting.SWbemDateTime")
Set dtmEndDate = CreateObject("WbemScripting.SWbemDateTime")
'DateToCheck = CDate("5/18/2009")
DateToCheck = date
dtmStartDate.SetVarDate DateToCheck, CONVERT_TO_LOCAL_TIME
dtmEndDate.SetVarDate DateToCheck + 1, CONVERT_TO_LOCAL_TIME
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colEvents = objWMIService.ExecQuery _
("Select * from Win32_NTLogEvent Where TimeWritten >= '" _
& dtmStartDate & "' and TimeWritten < '" & dtmEndDate & "'")
For Each objEvent in colEvents
If objEvent.Eventcode = EventNu And (objEvent.LogFile = EventLog) Then
'Wscript.Echo "Category: " & objEvent.Category
Wscript.Echo "Computer Name: " & objEvent.ComputerName
Wscript.Echo "Event Code: " & objEvent.EventCode
Wscript.Echo "Message: " & objEvent.Message
' Wscript.Echo "Record Number: " & objEvent.RecordNumber
' Wscript.Echo "Source Name: " & objEvent.SourceName
Wscript.Echo "Time Written: " & objEvent.TimeWritten
Wscript.Echo "Event Type: " & objEvent.Type
' Wscript.Echo "User: " & objEvent.User
Wscript.Echo objEvent.LogFile
End if
Next
'Next
WScript.Echo EventNu
WScript.Echo EventLog
The arguments passed are treated as being of type string. However, EventNu should be an integer. You therefore have to convert the arguments to the correct type using CInt and CStr:
EventNu = CInt(WScript.Arguments.Item(0))
EventLog = CStr(WScript.Arguments.Item(1))