vbs read from file and parse it to the batch file - batch-file

I had a script which worked on win xp but beacuse some of the methods are not available anymore I had to rewrite the script and use mshta.exe.
VBS script should do two things:
Read from file
Parse the info to the batch file
I have done the 1st bit but in the 2nd part I am getting an error. Could you please point me to the right direction?
Option Explicit
Dim objFso
Dim strFileName
Dim strFile
Dim objShell
Dim cimv2
Dim RemoteMachine
Dim YesNo
Dim out
Dim crt
Dim objDialog, intResult
Dim objTextFile, strText, iintresult
Dim objExec, strMSHTA, wshShell
mainMenu
Sub mainMenu()
do
out = inputbox("Choose option:" & vbcr & "1 - Deployment" & vbcr & "0 - Exit", "Menu", "0")
If out="1" then
call SelectFile
End If
If out="0"
then WScript.Quit
End if
loop
End Sub
Sub bgInfo(param)
YesNo = Msgbox("deployment? " & param, 4)
if YesNo = vbYes Then
do while not strMSHTA.AtEndOfStream
RemoteMachine = strMSHTA.ReadLine()
On Error Resume Next
objShell.Run "bginfo.bat " & RemoteMachine, 1, true
On Error Goto 0
loop
end if
End Sub
Sub SelectFile( )
strMSHTA = "mshta.exe ""about:" & "<" & "input type=file id=FILE>" _
& "<" & "script>FILE.click();new ActiveXObject('Scripting.FileSystemObject')" _
& ".GetStandardStream(1).WriteLine(FILE.value);close();resizeTo(0,0);" & "<" & "/script>"""
Set wshShell = CreateObject( "WScript.Shell" )
Set objExec = wshShell.Exec( strMSHTA )
intResult = objExec.StdOut.ReadLine( )
msgbox iintresult
If intResult <> "" Then
call bgInfo(intResult)
End If
Set objExec = Nothing
Set wshShell = Nothing
End Sub
Set objFso = Nothing
Set strFileName = Nothing
Set strFile = Nothing
Set objShell = Nothing
Set cimv2 = Nothing
Set RemoteMachine = Nothing
Set fso = Nothing
I am getting an error in line 33 char 5
Error: Object required: strMSHTA
thank you! :)

I had to add this code:
Set objFso = CreateObject("Scripting.FileSystemObject")
set strFile = objFso.OpenTextFile(param2, 1, True)
Set objShell = WScript.CreateObject("Wscript.Shell")`

Related

The Outlook VBA script sends the selected data to the SQL database

I have a simple VBA script in Outlook 2019, script zips an attachment before sending an email, creates a new email, attaches an attachment, and sends it to the recipient. My goal is to save selected data to SQL database, Such as .To,From and zip archive as binaryattachment.zip. I have a problem finding a command to send INSERT INTO to the database, is there such a possibility?
VBA script:
#If VBA7 Then
Private Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal milliseconds As LongPtr) 'MS Office 64 Bit
#Else
Private Declare Sub Sleep Lib "kernel32" (ByVal milliseconds As Long) 'MS Office 32 Bit
#End If
Function FileExists(FilePath As String) As Boolean
Dim TestStr As String
TestStr = ""
On Error Resume Next
TestStr = Dir(FilePath)
On Error GoTo 0
If TestStr = "" Then
FileExists = False
Else
FileExists = True
End If
End Function
Sub MainFunction()
Const cstrFolderAttachment As String = "C:\attachments\"
'Test 32/64 bit
Dim PathZipProgram As String
PathZipProgram = "C:\Program Files\7-Zip\7z.exe"
If Not FileExists(PathZipProgram) Then
PathZipProgram = "C:\Program Files (x86)\7-Zip\7z.exe"
End If
'Password lenght
Const cintLenghtPassword As Integer = 8
'User signature file
Const cstrFileSigntature As String = "signature.htm"
Dim objMail As Outlook.MailItem
Dim objNewMail1 As Outlook.MailItem
Dim objNewMail2 As Outlook.MailItem
Dim objAttachment As Attachment
Dim objWord As Object
Dim objDocument As Object
Dim objFSO As Object
Dim objTextStream As Object
Dim strTo As String
Dim strSubject As String
Dim strBody As String
Dim strCommand As String
Dim strFilePath As String
Dim objWordRange As Object
Dim strMessage As String
Dim objApp As Object
Dim objInsp As Object
'Set objApp = GetObject("", "Outlook.Application")
'Set objInsp = objApp.ActiveInspector.CurrentItem
Dim signature As String
Dim objNS As Outlook.NameSpace
Dim objFolderItem As Outlook.Folder
Select Case Application.ActiveWindow.Class
Case olExplorer
Set objMail = ActiveExplorer.Selection.Item(1)
Case olInspector
Set objMail = ActiveInspector.CurrentItem
End Select
strMessage = "Subject: " & objMail.Subject & vbCrLf & vbCrLf & "Message: " & vbCrLf & objMail.Body
'Clear subfolder
On Error Resume Next
Kill cstrFolderAttachment & "*.*"
Kill cstrFolderAttachment & "Zip\*.*"
On Error GoTo 0
Set objMail = Application.ActiveInspector.CurrentItem
Set objNS = Application.GetNamespace("MAPI")
Set objFolderItem = objNS.Folders.Item("name.surname#domaind.com").Folders.Item("Temp")
objMail.Move objFolderItem
objDokument.Close False
'clear variables
Set objDokument = Nothing
Set objWord = Nothing
'save all attechments to folder
For Each objAttachment In objMail.Attachments
objAttachment.SaveAsFile cstrFolderAttachment & objAttachment.FileName
Next objAttachment
'7zip comprimation
strSource = cstrFolderAttachment & "*.*"
strDestination = cstrFolderAttachment & "Zip\attachment.zip"
strPassword = RandomPassword(cintLenghtPassword)
strCommand = """" & PathZipProgram & """ a -tzip """ & strCil & _
""" -p" & strPassword & " """ & strSource & """"
Shell strCommand
'Application.Wait (Now + TimeSerial(0, 0, cintBreak))
Call Sleep(1000 * cintBreak)
'FSO
strstrFilePath = Environ("appdata") & _
"\Microsoft\Signatures\" & cstrFileSigntature
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextStream = _
objFSO.GetFile(cstrFileSigntature).OpenAsTextStream(1, -2)
strSignature = objTextStream.ReadAll
objTextStream.Close
'clear variables
Set objTextStream = Nothing
Set objFSO = Nothing
Set objNewMail1 = Application.CreateItem(olMailItem)
With objNewMail1
'To
For Each recip In objMail.Recipients
Set newRecip = .Recipients.Add(recip.Address)
newRecip.Type = recip.Type
Next
.Subject = strSubject
.BodyFormat = olFormatHTML
.HTMLBody = strSignature
.Attachments.Add cstrFolderAttachment & "Zip\attachment.zip"
.Display
.Send
End With
objNewMail1.Close olSave
'clear variables
Set objMail = Nothing
Set objNewMail1 = Nothing
i = MsgBox("Email sended.", , "info box")
End Sub
Private Function RandomPassword(Delka As Integer)
'Dave Hawley
Dim i As Integer
Dim strHeslo As String
Randomize
For i = 1 To Lenght
If i Mod 2 = 0 Then
strPassword = Chr(Int((90 - 65 + 1) * Rnd + 65)) & strPassword
Else
strPassword = Int((9 * Rnd) + 1) & strPassword
End If
Next i
RandomPassword = strPassword
End Function
Database structure:
ID INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
to_email VARCHAR(100) NOT NULL,
from_email VARCHAR(100) NOT NULL,
attachment VARBINARY(MAX) NOT NULL,
date_create DATETIME NOT NULL,
file_size INT NOT NULL

Update Access front end through batch file?

Looking to see if there would be a way for users to update their MS Access db front end by clicking a button. The button would then trigger a batch file that would grab the file from a location on our server, and overwrite the current db on the users local PC. All done within one office, so network addresses would be all the same.
Location of file to copy: 10.0.0.0.5/Data/DB/Database.accdb
Location of file to overwrite: c:\DB\Database.accdb
Any ideas? Ideally I would love for someone to write a nice exe file that deletes the older version and installs the newer version, but can't write that kind of code.
Write a batch file to retrieve the newer version of the front end from it's source and copy it into the folder where the user's copy of the front end file lives. Add a line at the end of the batch file to launch msacess.exe with the filename of your front end program as a command line parameter.
The batch file can be located anywhere, but I recommend locating it in the folder where your application front end will reside.
Create a Windows shortcut to the batch file, which can be placed on the users' Desktop or anywhere else the user expects to launch the application.
Bonus points for dressing up the shortcut to the batch file by changing the icon: Right-click|Properties|Change icon... button.
A nice article on the topic can be found here:
Deploy and update a Microsoft Access application in a Citrix environment
It uses neither a bat, nor an exe, but a VBscript:
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
You could probably convert it to PowerShell, which I would use today.
I use a vbscript for that purpose. I only update the path for the file due to be copied and then I sent an email to the users with a link to the script. The user clicks the link and the script is executed.
Copy the code below to a text file and save it as .vbs. Don't forget to set the path for the file due to be copied.
Option Explicit
Call Main()
Private Sub Main()
const folderFrom = "\\Somepath\Somefolder\" 'Folder: Must supply backslash
const fileName = "SomeFile.accdb" 'File name with extension
const overwrite = -1 'OverWrite = True
'Ask user to proceed
dim msg
msg = "The script will copy the file below to your desktop. " & vbNewLine & vbNewLine & _
String(75,"_") & vbNewLine & vbNewLine & _
"File: " & " " & " " & " " & " " & " " & " " & " '" & fileName & "' " & vbNewLine & _
"Folder: " & " " & " '" & folderFrom & "' " & vbNewLine & _
String(75,"_") & vbNewLine & vbNewLine & _
"Proceed?"
if MsgBox(msg, vbYesNo + vbQuestion, "FileCopy Confirmation") = vbNo then exit sub
on error resume next
dim filesys
set filesys = CreateObject("Scripting.FileSystemObject")
'File exists in folder?
if not filesys.FileExists(folderFrom & fileName) then
MsgBox "File not found. Task aborted. ", vbOKOnly + vbExclamation, "Attention:"
exit sub
end if
'User's desktop path
dim desktopPath
desktopPath = CreateObject("WScript.Shell").SpecialFolders("Desktop") & "\"
'Copy file
filesys.CopyFile folderFrom & fileName, desktopPath & fileName, overwrite
'Validate file copied
if filesys.FileExists(desktopPath & fileName) then
Msgbox "File copied successfully.", vbOKOnly + vbInformation, "Success!"
else
MsgBox "File could not be copied... ", vbOKOnly + vbExclamation, "Copy Failed..."
end if
End Sub
Suggestion:
You shouldn't overwrite the existing front-end database but instead you should consider versioning e.g. v2.0, v2.1, v2.2 etc. for better tracking.

If Then not working

I've searched a lot about this problem, but I haven't found anything specific to this case. I'm trying to run a script that grabs all hosts from AD, then checks each one for a specific file. Two txt files are created, one with and one without. The problem I'm having is that all host names are added to the 'without' file and the 'with' file is empty, but I know for a fact that both lists should have hosts listed. I know the loop is working because all the host names are listed, but it fails to apply the if/then check. I apologize for the crudity of my script, I'm VERY new to this. I would GREATLY appreciate any tips...
Const ADS_SCOPE_SUBTREE = 2
Dim cn
Set cn = CreateObject("ADODB.Connection")
cn.Provider = "ADsDSOObject"
cn.Open "Active Directory Provider"
Dim cmd
Set cmd = CreateObject("ADODB.Command")
Set cmd.ActiveConnection = cn
Dim ou
ou = "DC=mydomain,DC=COM"
cmd.CommandText = "SELECT name " & _
"FROM 'LDAP://" & ou & "' " & _
"WHERE objectClass='computer' " & _
"ORDER BY name"
cmd.Properties("Page Size") = 1000
cmd.Properties("Searchscope") = ADS_SCOPE_SUBTREE
Const ForAppending = 8
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
Dim yesFile
Set yesFile = fso.OpenTextFile("pcswithsw.txt", ForAppending, True)
Dim noFile
Set noFile = fso.OpenTextFile("pcswithoutsw.txt", ForAppending, True)
Dim rs
Set rs = cmd.Execute
strComputer = rs(0)
rs.MoveFirst
Do Until rs.EOF
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colFiles = objWMIService.ExecQuery("Select * From CIM_DataFile Where Name = 'C:\\somefile.exe'")
If colFiles.Count = 0 Then
noFile.WriteLine rs(0)
Else
yesFile.WriteLine rs(0)
End If
rs.MoveNext
Loop
yesFile.Close
noFile.Close
Set yesFile = Nothing
Set noFile = Nothing
Set fso = Nothing
Figured it out finally. I loaded the list of hosts into an array, then fed the array to the If/Then statement. It runs slowly, but the majority of the processing time is the script waiting for non-existent hosts to reply (need to clean up AD).
Const ADS_SCOPE_SUBTREE = 2
Const ForAppending = 8
Dim hostArray()
Dim cn
Set cn = CreateObject("ADODB.Connection")
cn.Provider = "ADsDSOObject"
cn.Open "Active Directory Provider"
Dim cmd
Set cmd = CreateObject("ADODB.Command")
Set cmd.ActiveConnection = cn
Dim ou
ou = "DC=mydomain,DC=COM"
cmd.CommandText = "SELECT name " & _
"FROM 'LDAP://" & ou & "' " & _
"WHERE objectClass='computer' " & _
"ORDER BY name"
cmd.Properties("Page Size") = 1000
cmd.Properties("Searchscope") = ADS_SCOPE_SUBTREE
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
Dim outFile
Set outFile = fso.OpenTextFile("computers.txt", ForAppending, True)
Dim yesFile
Set yesFile = fso.OpenTextFile("pcswithsw.txt", ForAppending, True)
Dim noFile
Set noFile = fso.OpenTextFile("pcswithoutsw.txt", ForAppending, True)
Dim j
j=0
Dim rs
Set rs = cmd.Execute
rs.MoveFirst
Do Until rs.EOF
REDIM PRESERVE hostArray(j)
for i = 0 to rs.EOF
hostArray(j)=rs(0)
outFile.WriteLine rs(0)
rs.MoveNext
i = i + 1
j = j + 1
next
Loop
For Each strComputer in hostArray
On Error Resume Next
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colFiles = objWMIService.ExecQuery("Select * From CIM_DataFile Where Name = 'C:\\folder\\subfolder\\file.ext'")
If colFiles.Count = 0 Then
noFile.WriteLine strComputer
Else
yesFile.WriteLine strComputer
End If
Next
yesFile.Close
noFile.Close
Set yesFile = Nothing
Set noFile = Nothing
Set fso = Nothing
msgbox("All done")

Read the content of the Zip file(ex.txt) without extracting the zip file

I'm really new to Access VBA. I have a problem in Access code could you help me with a request mentioned below?
I have file with names like ex.zip. In this example, the Zip file contains only one file with the same name(ie. `ex.txt'), which is quite large file. I don't want to extract the zip file every time.Hence I need to read the content of the file(ex.txt) without extracting the zip file. I tried some code like below But i can't read the content of the file and can't stores the content in the variable in Access VBA.
How do I read the content of the file and stores it in the variable?
I have tried some code in VBA to read the zipped text But i didn't make any sense..
Here's the code for zipping & unzipping. If you look at it the unzip part, you'll see where it reads the zip file like a directory. Then you can choose if you want to extract that file.
Private Declare Sub Sleep Lib "kernel32" ( _
ByVal dwMilliseconds As Long _
)
Public Sub Zip( _
ZipFile As String, _
InputFile As String _
)
On Error GoTo ErrHandler
Dim FSO As Object 'Scripting.FileSystemObject
Dim oApp As Object 'Shell32.Shell
Dim oFld As Object 'Shell32.Folder
Dim oShl As Object 'WScript.Shell
Dim I As Long
Dim l As Long
Set FSO = CreateObject("Scripting.FileSystemObject")
If Not FSO.FileExists(ZipFile) Then
'Create empty ZIP file
FSO.CreateTextFile(ZipFile, True).Write "PK" & Chr(5) & Chr(6) & String(18, vbNullChar)
End If
Set oApp = CreateObject("Shell.Application")
Set oFld = oApp.NameSpace(CVar(ZipFile))
I = oFld.Items.Count
oFld.CopyHere (InputFile)
Set oShl = CreateObject("WScript.Shell")
'Search for a Compressing dialog
Do While oShl.AppActivate("Compressing...") = False
If oFld.Items.Count > I Then
'There's a file in the zip file now, but
'compressing may not be done just yet
Exit Do
End If
If l > 30 Then
'3 seconds has elapsed and no Compressing dialog
'The zip may have completed too quickly so exiting
Exit Do
End If
DoEvents
Sleep 100
l = l + 1
Loop
' Wait for compression to complete before exiting
Do While oShl.AppActivate("Compressing...") = True
DoEvents
Sleep 100
Loop
ExitProc:
On Error Resume Next
Set FSO = Nothing
Set oFld = Nothing
Set oApp = Nothing
Set oShl = Nothing
Exit Sub
ErrHandler:
Select Case Err.Number
Case Else
MsgBox "Error " & Err.Number & ": " & Err.Description, vbCritical, "Unexpected error"
End Select
Resume ExitProc
Resume
End Sub
Public Sub UnZip( _
ZipFile As String, _
Optional TargetFolderPath As String = vbNullString, _
Optional OverwriteFile As Boolean = False _
)
'On Error GoTo ErrHandler
Dim oApp As Object
Dim FSO As Object
Dim fil As Object
Dim DefPath As String
Dim strDate As String
Set FSO = CreateObject("Scripting.FileSystemObject")
If Len(TargetFolderPath) = 0 Then
DefPath = CurrentProject.Path & "\"
Else
If Not FSO.FolderExists(TargetFolderPath) Then
MkDir TargetFolderPath
End If
DefPath = TargetFolderPath & "\"
End If
If FSO.FileExists(ZipFile) = False Then
MsgBox "System could not find " & ZipFile & " upgrade cancelled.", vbInformation, "Error Unziping File"
Exit Sub
Else
'Extract the files into the newly created folder
Set oApp = CreateObject("Shell.Application")
With oApp.NameSpace(ZipFile & "\")
If OverwriteFile Then
For Each fil In .Items
If FSO.FileExists(DefPath & fil.Name) Then
Kill DefPath & fil.Name
End If
Next
End If
oApp.NameSpace(CVar(DefPath)).CopyHere .Items
End With
On Error Resume Next
Kill Environ("Temp") & "\Temporary Directory*"
'Kill zip file
Kill ZipFile
End If
ExitProc:
On Error Resume Next
Set oApp = Nothing
Exit Sub
ErrHandler:
Select Case Err.Number
Case Else
MsgBox "Error " & Err.Number & ": " & Err.Description, vbCritical, "Unexpected error"
End Select
Resume ExitProc
Resume
End Sub

VB script: if file exists then run if not then end

I'm looking to use a script to go about disabling a file (REAgentc.exe) on Windows 7 machines and if it does not exist (i.e. on XP machines) then end. Below is what I've got so far but can anyone assist me in implementing the rest of what I'm after? My knowledge on VB script is admittedly not great but any help that can be offered forward would be greatly appreciated, thanks.
'Declare Variables
Dim strApp
Dim arrPath
Dim strPath
Dim strAppPath
' main if statement to run the script and call functions and sub's
If (CheckRegistryForValue)= True Then
'msgbox( strPath & " I am here")
WScript.Quit (0)
Else
RunCommand
WriteRegkey
WScript.Quit (0)
End If
'Sub to run the REAgent disable command
Sub RunCommand
Set objShell = CreateObject("Wscript.Shell")
strApp = "C:\Windows\System32\REAgentc.exe /disable"
arrPath = Split(strApp, "\")
For i = 0 To Ubound(arrPath) - 1
strAppPath = strAppPath & arrPath(i) & "\"
Next
objShell.CurrentDirectory = strAppPath
objShell.Run(strApp)
End Sub
'Function to check registry for value, Return check registry for value
Function CheckRegistryForValue
Set WshShell = WScript.CreateObject("WScript.Shell")
On Error Resume Next
dong = wshShell.RegRead ("HKLM\SOFTWARE\REAgent\")
If (Err.Number <> 0) Then
CheckRegistryForValue = False
Else
CheckRegistryForValue = True
End If
End Function
' sub to write registery key to flag computers that the script has run On
Sub WriteRegkey
HKEY_LOCAL_MACHINE = &H80000002
strComputer = "."
Set ObjRegistry = GetObject("winmgmts:{impersonationLevel = impersonate}!\\" & strComputer & "\root\default:StdRegProv")
strPath = "SOFTWARE\REAgent\Script Complete"
Return = objRegistry.CreateKey(HKEY_LOCAL_MACHINE, strPath)
End Sub
You can modify your RunCommand to detect & run;
dim FSO, objShell, strApp
set FSO = CreateObject("Scripting.FileSystemObject")
set objShell = CreateObject("Wscript.Shell")
'//get system path
strApp = FSO.GetSpecialFolder(1) & "\REAgentc.exe"
if FSO.FileExists(strApp) then
'//no need to change directory as you have the full path
objShell.Run(strApp & " /disable")
else
'//does not exist
end if

Resources