vbs save and close all chrome and word documents - google-chrome

I am trying to create a vbscript that clears all my browser data in chrome, then closes all chrome windows.
I am having trouble closing word and outlook.
This it the code that works so far and clears chrome and closes the chrome browser:
Set WshShell = CreateObject("WScript.Shell")
set WshShell=WScript.CreateObject("WScript.Shell")
WshShell.run "chrome.exe"
Set WshShell = CreateObject("WScript.Shell")
set WshShell=WScript.CreateObject("WScript.Shell")
WshShell.run "chrome.exe"
WScript.Sleep (1000)
WScript.CreateObject("WScript.Shell").SendKeys("^h")
WScript.Sleep (2000)
WScript.CreateObject("WScript.Shell").SendKeys("{TAB}")
WScript.CreateObject("WScript.Shell").SendKeys("{TAB}")
WScript.CreateObject("WScript.Shell").SendKeys("{TAB}")
WScript.CreateObject("WScript.Shell").SendKeys("{ENTER}")
WScript.Sleep (2000)
WScript.CreateObject("WScript.Shell").SendKeys("{TAB}")
WScript.CreateObject("WScript.Shell").SendKeys("{TAB}")
WScript.CreateObject("WScript.Shell").SendKeys("{TAB}")
WScript.CreateObject("WScript.Shell").SendKeys("{TAB}")
WScript.CreateObject("WScript.Shell").SendKeys("{TAB}")
WScript.CreateObject("WScript.Shell").SendKeys("{TAB}")
WScript.CreateObject("WScript.Shell").SendKeys("{TAB}")
WScript.CreateObject("WScript.Shell").SendKeys("{TAB}")
WScript.CreateObject("WScript.Shell").SendKeys("{TAB}")
WScript.CreateObject("WScript.Shell").SendKeys("{ENTER}")
WshShell.AppActivate("Google Chrome")
WshShell.run "RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 8"
WshShell.run "RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 2"
WshShell.run "RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 1"
WshShell.run "RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 16"
WshShell.run "RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 32"
WshShell.run "RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 255"
Set objExec = Nothing : Set objShell = Nothing
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colProcessList = objWMIService.ExecQuery _
("Select * from Win32_Process Where Name = 'Chrome.exe'")
Set oShell = CreateObject("WScript.Shell")
For Each objProcess in colProcessList
oShell.Run "taskkill /im chrome.exe", , True
Next
Set objShell = CreateObject("WScript.Shell")
Set objExec = objShell.Exec("tasklist /fi " & Chr(34) & "imagename eq chrome.exe" & Chr(34))
If Not InStr(1, objExec.StdOut.ReadAll(), "INFO: No tasks", vbTextCompare) Then
objShell.Run "taskkill /f /t /im chrome.exe", 0, True
End If
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colProcessList = objWMIService.ExecQuery _
("Select * from Win32_Process Where Name = 'notepad.exe'")
For Each objProcess in colProcessList
objProcess.Terminate()
Next
I am trying to close all of the word documents open and save them, basically (control s). I would like all of this to happen in one VBS file so that I can send this to my friends, and they can use it too easily.
I have researched online, but haven't found what I am looking for.
All the websites that I have looked at have either, only show how to close all documents without saving them or have not shown the process in VBS, instead using VBA or another scripting language.
I would appreciate if someone could help me write my script!
:)

Save and close all documents:
'get a handle to the already running Word instance
On Error Resume Next
Set wd = GetObject(, "Word.Application")
On Error Goto 0
If Not IsEmpty(wd) Then
For Each doc In wd.Documents
doc.Save
doc.Close
Next
wd.Quit
End If
For closing all documents without saving change doc.Save to doc.Saved = True. That basically tells Word "this document was already saved, shut up".

Related

VBScript to recursively scrape a local intranet page for links

I've been tasked with identifying all of the many links we have on our team's intranet. The goal is to declutter (find duplicate links or dead links).
I wrote this script that will go to our page and scrape every link while identifying the file extension. What I'm not sure how to do is to make this recursive. Once it goes to our site and scrapes those links, if it finds another URL (such as htm or html) I want it to follow THAT link and scrape the same from there and continue on until every link associated with the initial URL is exhausted. I'd like it to create a type of hierarchy in the csv such as (example headers):
lvl0_Link_Title,lvl0_File_Type,lvl0_URL,lvl1_Link_Title,lvl1_File_Type,lvl1_URL,lvl2_Link_Title,lvl2_File_Type,lvl2_URL,lvl3_Link...etc.
Obviously, this would end up with a pretty massive csv. If there is a better/cleaner method to achieve the same, I'm open to it.
Set objWshShell = Wscript.CreateObject("Wscript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")
Set IE = CreateObject("internetexplorer.application")
on error resume next
filename = fso.GetParentFolderName(WScript.ScriptFullName) & "\URL_Dump_Oldsite.csv"
'==============================================
'Create headers for CSV
set output = fso.opentextfile(filename,2,true)
output.writeline "Link Title,File Type,URL"
output.close
'==============================================
IE.Visible = false
IE.Navigate "URL OF OUR INTRANET"
Do While IE.Busy or IE.ReadyState <> 4: WScript.sleep 100: Loop
Do Until IE.Document.ReadyState = "complete": WScript.sleep 100: Loop
for each url in ie.document.getelementsbytagname("a")
if not url.href is nothing then
ext = mid(url.href,instrrev(url.href,"."))
set output = fso.opentextfile(filename,8,true)
output.writeline replace(url.innertext,","," / ") & "," & ext & ",=HYPERLINK(" & chr(34) & url.href & chr(34) & ")"
output.close
end if
next
'===========================================
'Keyword filter for removal
Dim arrFilter
arrFilter = Array("bakpcweb", _
"aims", _
"element", _
"objid", _
"nodeid", _
"objaction", _
"javascript", _
"itemtype")
'===========================================
'Delete lines from csv file containing keywords
strFile1 = fso.GetParentFolderName(WScript.ScriptFullName) & "\URL_Dump_Oldsite.csv"
Set objFile1 = fso.OpenTextFile(strFile1)
Do Until objFile1.AtEndOfStream
i = 0
strLine1 = trim(lcase(objFile1.Readline))
for a = lbound(arrFilter) to ubound(arrFilter)
if instr(strLine1,arrFilter(a)) <> 0 then
i = i + 1
End If
next
if i = 0 then
strNewContents1 = strNewContents1 & strLine1 & vbCrLf
end if
Loop
objFile1.Close
Set objFile1 = fso.OpenTextFile(strFile1,2,true)
objFile1.Write strNewContents1
objFile1.Close
'===========================================
'Delete blank lines from csv file
strFile = fso.GetParentFolderName(WScript.ScriptFullName) & "\URL_Dump_Oldsite.csv"
Set objFile = fso.OpenTextFile(strFile)
Do Until objFile.AtEndOfStream
strLine = objFile.Readline
strLine = Trim(strLine)
If Len(strLine) > 0 Then
strNewContents = strNewContents & strLine & vbCrLf
End If
Loop
objFile.Close
Set objFile = fso.OpenTextFile(strFile,2,true)
objFile.Write strNewContents
objFile.Close
'===========================================
'Remove duplicate lines from csv file
Set objDictionary = CreateObject("Scripting.Dictionary")
strFile = fso.GetParentFolderName(WScript.ScriptFullName) & "\URL_Dump_Oldsite.csv"
Set objFile = fso.OpenTextFile(strFile)
Do Until objFile.AtEndOfStream
strLine = objFile.Readline
strLine = Trim(strLine)
If Not objDictionary.Exists(strLine) Then
objDictionary.Add strLine, strLine
End If
Loop
objFile.Close
Set objFile = fso.opentextfile(strFile,2,true)
For Each strKey in objDictionary.Keys
objFile.WriteLine strKey
Next
objFile.Close
objDictionary.clearall
'===========================================
wscript.echo "Done!"
ie.quit
wscript.quit
Thank you!
This might not be the answer you were expecting, but it sounds like you're reinventing the wheel here, and with a sub-standard tool. In my experience, I also wouldn't find the lvl0, lvl1 etc. format particularly useful when reporting later.
I would strongly recommend you instead use an existing program to scan your intranet, such as Xenu or for a more in-depth analysis, try Screaming Frog SEO Spider (free version is limited to about 500 pages, as I recall, but you can give it a try). These tools have features to save reports, which should suit your needs.
If that doesn't work for you, please comment or edit your answer to explain why you must do this yourself and report in the specified format.
Edit: Here's an example screenshot from the free Xenu program, which lists every resource it tried, its status, links in/out, and type, which can assist with your requirement to report on filetypes. It will also generate full HTML reports if you want stats.

VBS close all chrome tabs

I am trying to create this:
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colProcessList = objWMIService.ExecQuery _
("Select * from Win32_Process Where Name = 'Chrome.exe'")
Set oShell = CreateObject("WScript.Shell")
For Each objProcess in colProcessList
oShell.Run "taskkill /im chrome.exe", , True
Next
Dim iURL
Dim objShell
iURL = "www.google.com.au"
set objShell = CreateObject("Shell.Application")
objShell.ShellExecute "chrome.exe", iURL, "", "", 1
The code works, but if there are too many chrome tabs open, it doesn't close all tabs. There is also sometimes an error message in closing tabs.
One way to do it is opening Chrome in incognito mode so that you don't see the Restore Session error.
Dim objExec, objShell, iURL
Set objShell = CreateObject("WScript.Shell")
Set objExec = objShell.Exec("tasklist /fi " & Chr(34) & "imagename eq chrome.exe" & Chr(34))
If Not InStr(1, objExec.StdOut.ReadAll(), "INFO: No tasks", vbTextCompare) Then
objShell.Run "taskkill /f /t /im chrome.exe", 0, True
End If
iURL = "www.google.com.au"
objShell.Run "chrome.exe -incognito " & iURL
Set objExec = Nothing : Set objShell = Nothing
WScript.Quit

Deploy Access 2007 Database with SQL back end to Citrix for multiple users

Situation:
I recently took IT Support ownership of our Time Tracking database at my company (the old owner left). This was written in Access 2007 and uses SQL Server 2008 R2 Tables and views in the back end. We publish a locked (db.accde) version to our Citrix farm and users access it by logging into a citrix web portal and clicking on the icon for the Access Database. I have a need to move this from once server to a different server so the old one can be sunset. I tried simply copying the file on the existing server to the new server (which is running Office 2010 apps) and creating a new icon on the citrix portal to point to it.
Problem:
Now that it is there only 1 person can open it at a time (used to be usable by multiple users) Also it needs to know who I am (for appropriate permissions within the DB) and it doesn't seem to have a clue. It is giving errors related to the SQL connection. The way it figures out who you are and what permissions you should have is by checking Active Directory and if you belong to the correct NT group then you can have access to additional Forms, if not you only see the basic user forms. Right now everyone who opens it from Citrix only sees the "basic user forms" regardless of the NT Groups they are assigned to.
Question:
I am not an advanced developer when it comes to Access and VB. I also know very little about how Citrix works. I am wondering if when I copied the DB to the new server if there was something I didn't do that should have happened. For instance when you open the "existing link" which opens the "existing Access db" for a brief second there is a CMD screen that pops up and goes away prior to the access DB opening. on the new link that is not happening.
If anyone has any expertise they can toss my way to help me go down the right path of figuring this out it would be greatly appreciated.
For various reasons, it is a VBscript. PowerShell could be used as well.
The "trick" is to use the user's LocalAppData folder to host the accdb file as the user always has been granted full rights here.
It worked from the first attempt. The version number is caused by minor changes, including changed names of the local folders, only.
The users received a link to a read-only copy of the script in a shared folder and - when double-clicked - ran and created a shortcut on the user's desktop for future launch of the application. Users had by default Access 2010 installed so no runtime was needed.
The script carries out these tasks:
creates subfolders in the user's LocalAppData folder
kills the application should it be running
copies the current version of the application to the local folder
copies a second copy (launched by the first for background tasks)
creates/copies a shortcut
writes the security settings for the application in the Registry
launches the application (which then launches the background application)
The result is that the user at each launch updates the application, thus deployment of new application versions is "automatic".
Please study the in-line comments for details.
Option Explicit
' Launch script for PPT test/development/operation.
' Version 1.3.0
' 2013-09-15
' Cactus Data. Gustav Brock
Const DESKTOP = &H10
Const LOCALAPPDATA = &H1C
Dim objFSO
Dim objAppShell
Dim objDesktopFolder
Dim objLocalAppDataFolder
Dim objLocalFolder
Dim objRemoteFolder
Dim strLocalFolder
Dim strRemoteFolder
Dim strDesktopFolder
Dim strLocalAppDataFolder
Dim strLocalAppDataDsgFolder
Dim strLocalAppDataDsgPptFolder
Dim strDsgSubfolder
Dim strPptSubfolder
Dim strPptAppSubfolder
Dim strPptNcSuffix
Dim strAppName
Dim strAppSuffix
Dim strShortcutName
Dim strAppLocalPath
Dim strAppLocalBackPath
Dim strAppRemotePath
Dim strShortcutLocalPath
Dim strShortcutRemotePath
Dim strRegPath
Dim strRegKey
Dim strRegValue
Dim booNoColour
Dim varValue
' Adjustable parameters.
strDsgSubfolder = "DSG"
strPptSubfolder = "PPT"
strPPtNcSuffix = "NC"
' ---------------------------------------------------------------------------------
' Uncomment one folder name only:
'strPptAppSubfolder = "Development"
strPptAppSubfolder = "Operations"
'strPptAppSubfolder = "Test"
' ---------------------------------
' Indicate if the script is for the normal version (0) or the no-colour version (1):
booNoColour = 0
' ---------------------------------------------------------------------------------
strRemoteFolder = "K:\_Shared\Sales Planning\Environments\" & strPptAppSubfolder
If booNoColour = 1 Then
strAppSuffix = strPptNcSuffix
Else
strAppSuffix = ""
End If
strAppName = "SalesPlanningTool" & strAppSuffix & ".accdb"
If strPptAppSubfolder = "Operations" Then
If strAppSuffix = "" Then
strShortcutName = "RunPPT.lnk"
Else
strShortcutName = "RunPPT " & strAppSuffix & ".lnk"
End If
Else
If strAppSuffix = "" Then
strShortcutName = "RunPPT " & strPptAppSubfolder & ".lnk"
Else
strShortcutName = "RunPPT " & strAppSuffix & " " & strPptAppSubfolder & ".lnk"
End If
End If
' Enable simple error handling.
On Error Resume Next
' Find user's Desktop and AppData\Local folder.
Set objAppShell = CreateObject("Shell.Application")
Set objDesktopFolder = objAppShell.Namespace(DESKTOP)
strDesktopFolder = objDesktopFolder.Self.Path
Set objLocalAppDataFolder = objAppShell.Namespace(LOCALAPPDATA)
strLocalAppDataFolder = objLocalAppDataFolder.Self.Path
' Dynamic parameters.
strLocalAppDataDsgFolder = strLocalAppDataFolder & "\" & strDsgSubfolder
strLocalAppDataDsgPptFolder = strLocalAppDataDsgFolder & "\" & strPptSubfolder
strLocalFolder = strLocalAppDataDsgPptFolder & "\" & strPptAppSubfolder
strAppLocalPath = strLocalFolder & "\" & strAppName
strShortcutLocalPath = strDesktopFolder & "\" & strShortcutName
' Permanent parameters.
strAppRemotePath = strRemoteFolder & "\" & strAppName
strShortcutRemotePath = strRemoteFolder & "\" & strShortcutName
' Create the File System Object.
Set objFSO = CreateObject("Scripting.FileSystemObject")
If Not objFSO.FolderExists(strRemoteFolder) Then
Call ErrorHandler("No access to " & strRemoteFolder & ".")
Else
Set objRemoteFolder = objFSO.GetFolder(strRemoteFolder)
' If local folder does not exist, create the folder.
If Not objFSO.FolderExists(strLocalFolder) Then
If Not objFSO.FolderExists(strLocalAppDataDsgFolder) Then
Set objLocalFolder = objFSO.CreateFolder(strLocalAppDataDsgFolder)
If Not Err.Number = vbEmpty Then
Call ErrorHandler("Folder " & strLocalAppDataDsgFolder & " could not be created.")
End If
End If
If Not objFSO.FolderExists(strLocalAppDataDsgPPtFolder) Then
Set objLocalFolder = objFSO.CreateFolder(strLocalAppDataDsgPptFolder)
If Not Err.Number = vbEmpty Then
Call ErrorHandler("Folder " & strLocalAppDataDsgPptFolder & " could not be created.")
End If
End If
If Not objFSO.FolderExists(strLocalFolder) Then
Set objLocalFolder = objFSO.CreateFolder(strLocalFolder)
If Not Err.Number = vbEmpty Then
Call ErrorHandler("Folder " & strLocalFolder & " could not be created.")
End If
End If
End If
Set objLocalFolder = objFSO.GetFolder(strLocalFolder)
End If
If Not objFSO.FileExists(strAppRemotePath) Then
Call ErrorHandler("The application file:" & vbCrLf & strAppRemotePath & vbCrLF & "could not be found.")
Else
' Close a running PPT.
Call KillTask("PPT")
' Wait while TaskKill is running twice to close the instance(s) of PPT and PPT Background.
Call AwaitProcess("taskkill.exe")
Call KillTask("PPT Background")
' Wait while TaskKill is running twice to close the instance(s) of PPT and PPT Background.
Call AwaitProcess("taskkill.exe")
' Copy app to local folder.
If objFSO.FileExists(strAppLocalPath) Then
objFSO.DeleteFile(strAppLocalPath)
If Not Err.Number = 0 Then
Call ErrorHandler("The application file:" & vbCrLf & strAppName & vbCrLF & "can not be refreshed/updated. It may be in use.")
End If
End If
If objFSO.FileExists(strAppLocalPath) Then
Call ErrorHandler("The local application file:" & vbCrLf & strAppLocalPath & vbCrLF & "could not be replaced.")
Else
objFSO.CopyFile strAppRemotePath, strAppLocalPath
If Not Err.Number = vbEmpty Then
Call ErrorHandler("Application could not be copied to " & strLocalFolder & ".")
End If
' Create copy for PPT Background.
strAppLocalBackPath = Replace(Replace(strAppLocalPath, ".accdb", ".accbg"), "SalesPlanningTool", "SalesPlanningToolBack")
objFSO.CopyFile strAppLocalPath, strAppLocalBackPath
If Not Err.Number = vbEmpty Then
Call ErrorHandler("Background application could not be copied to " & strLocalFolder & ".")
End If
End If
' Copy shortcut.
objFSO.CopyFile strShortcutRemotePath, strShortcutLocalPath
If Not Err.Number = vbEmpty Then
Call ErrorHandler("Shortcut could not be copied to your Desktop.")
End If
End If
' Write Registry entries for Access security.
strRegKey = "HKEY_CURRENT_USER\Software\Microsoft\Office\14.0\Access\Security\"
strRegValue = "VBAWarnings"
strRegPath = strRegKey & strRegValue
varValue = 1
Call WriteRegistry(strRegPath, varValue,"REG_DWORD")
strRegKey = strRegKey & "Trusted Locations\LocationLocalAppData\"
strRegValue = "AllowSubfolders"
strRegPath = strRegKey & strRegValue
varValue = 1
Call WriteRegistry(strRegPath, varValue, "REG_DWORD")
strRegValue = "Date"
strRegPath = strRegKey & strRegValue
varValue = Now
varValue = FormatDateTime(varValue, vbShortDate) & " " & FormatDateTime(varValue, vbShortTime)
Call WriteRegistry(strRegPath, varValue, "REG_SZ")
strRegValue = "Description"
strRegPath = strRegKey & strRegValue
varValue = "Local AppData"
Call WriteRegistry(strRegPath, varValue, "REG_SZ")
strRegValue = "Path"
strRegPath = strRegKey & strRegValue
varValue = strLocalAppDataFolder & "\"
Call WriteRegistry(strRegPath, varValue, "REG_SZ")
' Run PPT.
If objFSO.FileExists(strAppLocalPath) Then
Call RunApp(strAppLocalPath, False)
Else
Call ErrorHandler("The local application file:" & vbCrLf & strAppLocalPath & vbCrLF & "could not be found.")
End If
Set objRemoteFolder = Nothing
Set objLocalFolder = Nothing
Set objLocalAppDataFolder = Nothing
Set objDesktopFolder = Nothing
Set objAppShell = Nothing
Set objFSO = Nothing
WScript.Quit
' Supporting subfunctions
' -----------------------
Sub RunApp(ByVal strFile, ByVal booBackground)
Dim objShell
Dim intWindowStyle
' Open as default foreground application.
intWindowStyle = 1
Set objShell = CreateObject("WScript.Shell")
objShell.Run Chr(34) & strFile & Chr(34), intWindowStyle, False
Set objShell = Nothing
End Sub
Sub KillTask(ByVal strWindowTitle)
Dim objShell
Set objShell = CreateObject("WScript.Shell")
objShell.Run "TaskKill.exe /FI ""WINDOWTITLE eq " & strWindowTitle & """", 7, False
Set objShell = Nothing
End Sub
Sub AwaitProcess(ByVal strProcess)
Dim objSvc
Dim strQuery
Dim colProcess
Dim intCount
Set objSvc = GetObject("winmgmts:root\cimv2")
strQuery = "select * from win32_process where name='" & strProcess & "'"
Do
Set colProcess = objSvc.Execquery(strQuery)
intCount = colProcess.Count
If intCount > 0 Then
WScript.Sleep 300
End If
Loop Until intCount = 0
Set colProcess = Nothing
Set objSvc = Nothing
End Sub
Sub WriteRegistry(ByVal strRegPath, ByVal varValue, ByVal strRegType)
' strRegType should be:
' "REG_SZ" for a string
' "REG_DWORD" for an integer
' "REG_BINARY" for a binary or boolean
' "REG_EXPAND_SZ" for an expandable string
Dim objShell
Set objShell = CreateObject("WScript.Shell")
Call objShell.RegWrite(strRegPath, varValue, strRegType)
Set objShell = Nothing
End Sub
Sub ErrorHandler(Byval strMessage)
Set objRemoteFolder = Nothing
Set objLocalFolder = Nothing
Set objLocalAppDataFolder = Nothing
Set objDesktopFolder = Nothing
Set objAppShell = Nothing
Set objFSO = Nothing
WScript.Echo strMessage
WScript.Quit
End Sub

How to run a script for every PC listed in .csv file?

I'm looking for help in being able to run a script against every PC listed in a csv using VBScript. Currently we are using a small script which we found on the "Hey, Scripting Guy blog" which gathers us the correct information regarding PC to Printer relationship but only on one manually specificed PC. This is a breakdown on what we're trying to achieve:
Take a list of PCs which are stored in a CSV.
Run the script listed below to query the values in the CSV and run the script against that value.
Once it has run the script against the values within the file, move on to the next PC in the CSV list.
strComputer = "PC-13699"
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colPrinters = objWMIService.ExecQuery("Select * From Win32_Printer")
For Each objPrinter in colPrinters
If objPrinter.Attributes And 64 Then
strPrinterType = "Local"
Else
strPrinterType = "Network"
End If
Wscript.Echo objPrinter.Name & " -- " & strPrinterType
Next
I haven't had much experience with VBS at all so I'm a complete novice with this language so please bear with me if I'm sounding stupid. Thanks for your help in advanced!
Assuming your CSV has a field named ComputerName for the computer names you could modify your script like this:
filename = "C:\path\to\your.csv"
Set csv = CreateObject("Scripting.FileSystemObject").GetFile(filename)
Set conn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
conn.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & csv.ParentFolder.Path & ";" & _
"Extended Properties=""text;HDR=YES;FMT=Delimited"""
rs.Open "SELECT * FROM [" & csv.Name & "]", conn
Do Until rs.EOF
strComputer = rs.Fields("ComputerName").Value
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colPrinters = objWMIService.ExecQuery("Select * From Win32_Printer")
For Each objPrinter in colPrinters
If objPrinter.Attributes And 64 Then
strPrinterType = "Local"
Else
strPrinterType = "Network"
End If
Wscript.Echo objPrinter.Name & " -- " & strPrinterType
Next
rs.MoveNext
Loop
rs.Close
conn.Close

write lines to file and when there 5 lines in needs to execute a statement vbscript

here is a code which i wanne run on background so no windowmessages. The meaning of it is that it checks a connection. If there isn't a connection it writes a error to a file. a function reads that file if there are 5 lines it should create a event-error. The problem is that the last part doesn't work correctly.
my qeustion is can somebody fix it or help me fixing it. Here is the code:
strDirectory = "Z:\text2"
strFile = "\foutmelding.txt"
strText = "De connectie is verbroken"
strWebsite = "www.helmichbeens.com"
If PingSite(strWebsite) Then WScript.Quit 'Website is pingable - no further action required
Set objFSO = CreateObject("Scripting.FileSystemObject")
RecordSingleEvent
If EventCount >= 5 Then
objFSO.DeleteFile strDirectory & strFile
Set WshShell = WScript.CreateObject("WScript.Shell")
strCommand = "eventcreate /T Error /ID 100 /L Scripts /D " & _
Chr(34) & "Test event." & Chr(34)
WshShell.Run strcommand
End if
'------------------------------------
'Record a single event in a text file
'------------------------------------
Sub RecordSingleEvent
If Not objFSO.FolderExists(strDirectory) Then objFSO.CreateFolder(strDirectory)
Set objTextFile = objFSO.OpenTextFile(strDirectory & strFile, 8, True)
objTextFile.WriteLine(Now & strText)
objTextFile.Close
End sub
'----------------
'Ping my web site
'----------------
Function PingSite( myWebsite )
Set objHTTP = CreateObject( "WinHttp.WinHttpRequest.5.1" )
objHTTP.Open "GET", "http://" & myWebsite & "/", False
objHTTP.SetRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MyApp 1.0; Windows NT 5.1)"
On Error Resume Next
objHTTP.Send
PingSite = (objHTTP.Status = 200)
On Error Goto 0
End Function
'-----------------------------------------------
'Counts the number of lines inside the text file
'-----------------------------------------------
Function EventCount()
strData = objFSO.OpenTextFile(strDirectory & strFile,ForReading).ReadAll
arrLines = Split(strData,vbCrLf)
EventCount = UBound(arrLines)
Set objFSO = Nothing
End Function
thats the code you can copy it to see it your self. i thank you for your time and intrest
Greets helmich
It doesn't work because function EventCount sets objFSO=nothing, so,
If EventCount >= 5 Then
objFSO.DeleteFile strDirectory & strFile
fails
Use the logevent method of the Shell object
If EventCount >= 5 Then
objFSO.DeleteFile strDirectory & strFile
Set WshShell = WScript.CreateObject("WScript.Shell")
Call WshShell.LogEvent(1, "Test Event")
End if
You don't need to run a separate command
Thats not the problem is this
Windows host script gives a error
Line:41
Char:2
Translation of error: the data required for this operation are not yet available
code: 80070057
source: WinHttp.WinHttpRequest
thats the problem and i do not know how to fix it
it has something to do that he can't read the lines in the txtfile and then not execute the create event command