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")
Related
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
Executing a macro from VBScript gives error :
Method CopyFromRecordset of object 'Range' failed
But It works fine, when I execute same from Excel workbook.
I tried executing from Excel workbook and it worked fine.
Here Is My VBA Code:
Set conn = New ADODB.Connection
conn.connectionString = "PROVIDER=SQLOLEDB;DATA SOURCE=localhost\SQLEXPRESS;INITIAL CATALOG=DEVDB; INTEGRATED SECURITY=sspi;"
Set rs = New ADODB.Recordset
str = "exec SP_Getcustomers #RequestID=" & requestID
rs.Open str, conn, adOpenStatic, adLockReadOnly
If Not IsEmptyRecordset(rs) Then
rs.MoveFirst
'Populate the first row of the sheet with recordset’s field names
i = 0
For Each fld In rs.Fields
ActiveWorkbook.Worksheets("Customer Table").Cells(1, i + 1).Value = rs.Fields.Item(i).Name
i = i + 1
Next fld
'Populate the sheet with the data from the recordset
ActiveWorkbook.Worksheets("Customer Table").Range("A2").CopyFromRecordset rs
End If
VB Script Code:
Dim path, macroname
path = ""
path = Wscript.Arguments.Item(2)
macroname = ""
macroname = Wscript.Arguments.Item(3)
Set objExcel = CreateObject("Excel.Application")
objExcel.Application.Run "'" & path & "'!" & macroname, WScript.Arguments.Item(0)
objExcel.Visible = False
objExcel.DisplayAlerts = False
objExcel.Application.Quit
Set objExcel = Nothing
We have a VBScript that downloads chunks of data from an SAP Business Object database into so-called slices, which are basically .csv files. The script worked perfectly so far, I haven't really had to look into it at all. But the failure now is this:
The script file section this error refers to is the dbConn.Execute(strSQL) line in the below code (5th from below).
What I tried so far, was to add these commands but they don't seem to solve anything:
'dbConn.ConnectionTimeout = 100
'dbConn.CommandTimeout = 100
The script itself (not all of it, I'm not sure the rest is needed):
Sub subRunFilesInFolder(strFolder)
Dim FSO, objFolder, objFiles
Dim i, intTS, intTS_file_start, ts, tsKillBefore, TS_file_start, strModelName
Dim dbConn, RST, RST2, strSQL
Dim strVBSmodel
Dim blRunIt
'INIs
strModelName = "bo_vbs_runner_1.5 "
strConn = "DRIVER={SQL Server};SERVER=EUBASEURCIREP01;UID=ser_login;PWD=ser_login;DATABASE=ser"
strComputer = FunstrComputerName
strBORunner = "\\Eubaseurcirep01\reporting\DEVELOPMENT\BO\Automation\Models\BO_auto_run.xlsb"
'Sets
Set dbConn = CreateObject("ADODB.Connection")
Set RST = CreateObject("ADODB.RecordSet")
Set RST2 = CreateObject("ADODB.RecordSet")
Set WshShell = WScript.CreateObject("WScript.Shell")
Set FSO = Wscript.CreateObject("Scripting.FileSystemObject")
Set objFolder = FSO.GetFolder(strFolder)
Set objFiles = objFolder.Files
Set appExcel = CreateObject("Excel.Application")
'dbConn.ConnectionTimeout = 100
'dbConn.CommandTimeout = 100
strVBSmodel = strModelName & strComputer & " " & FunstrUserName & " " & funCurrProcessId & " " & FunGetProcessIDCurrentOfExcel(strComputer)
appExcel.Application.Visible = False
appExcel.Displayalerts = False
Set objBORunner = appExcel.Workbooks.Open(strBORunner)
dbConn.Open strConn
ts = FunGetServerNow(dbConn,RST)
tsKillBefore = DateAdd("N", -15, ts)
intTS = funTimeStampToInteger(FunGetServerNow(dbConn, RST))
'Get ReportDate
strSQL = "SELECT yyyymmdd FROM map.reportdate WHERE dtAct=cast(GETDATE() as DATE);"
RST.Open strSQL, dbConn
If RST.EOF Then
strReportDate="99991231"
Else
strReportDate=RST.fields(0).value
End If
RST.close
'Kill stucked excel and vbs processes
strSQL = "SELECT distinct * FROM [ser].[bo].[_log] WHERE [proc]='BO VBS' AND result_text='started' AND end_timestamp<" & funTimeStampToInteger(tsKillBefore) & _
" AND lower(model) like '% " & LCase(strComputer) & " %';"
RST.Open strSQL,dbConn
If RST.EOF Then 'Nothing to kill
Else
Do While Not RST.EOF
strOldVBS = split(RST.fields("model"), " ")(3)
strOldExcel = split(RST.fields("model"), " ")(4)
Call SubKillProcessIDOnstrComputer(strComputer, strOldVBS)
Call SubKillProcessIDOnstrComputer(strComputer, strOldExcel)
strSQL = "UPDATE [ser].[bo].[_log] SET result_text='stopped', end_timestamp='" & funTimeStampToInteger(FunGetServerNow(dbConn,RST2)) & "' " & _
"WHERE [proc]='BO VBS' AND result_text='started' AND model='" & RST.fields("model").value & "' AND parameters='" & _
RST.fields("parameters").value & "';"
dbConn.Execute(strSQL)
RST.MoveNext
Loop
End If
RST.close
To Decode 0x8004nnnn Errors
HResults with facility code 4 means the HResult contains OLE errors (0x0 =
to 0x1ff) while the rest of the range (0x200 onwards) is component =
specific errors so 20e from one component will have a different meaning =
to 20e from another component.
You are lucky as your component is telling you it's OLDB with it's error - TIMEOUT
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")`
I am making a .MDB file which include a ms access database and a form made with vb 6. I am using ms access 2000, and I need to connect to both my local database in the MDB, and a remote MS SQL 2005 database.
In the below code, I can use a msgbox to display the value return from the result set, but when try to output it in a textBox, e.g: txtStatus.Value = txtStatus.Value & rstRecordSet.Fields(1) & vbCrLf, it just hangs. And the method show in the original example from the tutorial got a method of Debug.Print something, but it turns out didn't do anything which I can see. I mean, VB doesn't have a console panel, where will the print statement goes to?
The code with got error:
Function Testing()
On Error GoTo Error_Handling
Dim conConnection As New ADODB.Connection
Dim cmdCommand As New ADODB.Command
Dim rstRecordSet As New ADODB.Recordset
conConnection.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & _
App.Path & "\" & CurrentDb.Name & ";"
conConnection.CursorLocation = adUseClient
With cmdCommand
.ActiveConnection = conConnection
.CommandText = "SELECT * FROM Opt_In_Customer_Record;"
.CommandType = adCmdText
End With
With rstRecordSet
.CursorType = adOpenStatic
.CursorLocation = adUseClient
.LockType = adLockOptimistic
.Open cmdCommand
End With
If rstRecordSet.EOF = False Then
rstRecordSet.MoveFirst
Do
MsgBox "Record " & rstRecordSet.AbsolutePosition & " " & _
rstRecordSet.Fields(0).Name & "=" & rstRecordSet.Fields(0) & " " & _
rstRecordSet.Fields(1).Name & "=" & rstRecordSet.Fields(1)
rstRecordSet.MoveNext
Loop Until rstRecordSet.EOF = True
End If
conConnection.Close
Set conConnection = Nothing
Set cmdCommand = Nothing
Set rstRecordSet = Nothing
Exit Function
Error_Handling:
MsgBox "Error during function Testing!"
Exit Function
End Function
I thought it was a joke at the beginning ;-)
Anyway I assume you're talking about ADO, as in your title.
Here you can find stuff.
This site will help you with the connection strings for different database.
The difference between access and sql server using ADO it is exactly the connection string.
I would suggest you to avoid Remote Data Controls cause make your life simpler at the beginning but then you have to struggle with them cause they don't work properly.
This is an example of connection and fetch of data:
Dim cnn As New ADODB.Connection
Dim cmd As New ADODB.Command
Dim strSql As String
cnn.ConnectionString = _
"Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=m:\testdbSource\testSource.mdb;" & _
"User Id=admin;Password=;"
cnn.Open
cmd.ActiveConnection = cnn
cmd.CommandType = adCmdText
cmd.CommandText = "select * from tblSource"
cmd.Execute
Set cmd = Nothing
cnn.Close
Set cnn = Nothing
This sample works for me:
Function Testing()
On Error GoTo Error_Handling
Dim MyDb As String
Dim conConnection As New ADODB.Connection
Dim cmdCommand As New ADODB.Command
Dim rstRecordSet As New ADODB.Recordset
MyDb = "db1.mdb"
With conConnection
.Provider = "Microsoft.Jet.OLEDB.4.0"
.ConnectionString = App.Path & "\" & MyDb
.Open
End With
With cmdCommand
.ActiveConnection = conConnection
.CommandText = "SELECT * FROM Opt_In_Customer_Record;"
.CommandType = adCmdText
End With
With rstRecordSet
.CursorType = adOpenStatic
.CursorLocation = adUseClient
.LockType = adLockOptimistic
.Open cmdCommand
End With
Do While Not rstRecordSet.EOF
MsgBox "Record " & rstRecordSet.AbsolutePosition & " " & _
rstRecordSet.Fields(0).Name & "=" & rstRecordSet.Fields(0) & " " & _
rstRecordSet.Fields(1).Name & "=" & rstRecordSet.Fields(1)
rstRecordSet.MoveNext
Loop
conConnection.Close
Set conConnection = Nothing
Set cmdCommand = Nothing
Set rstRecordSet = Nothing
Exit Function
Error_Handling:
MsgBox "Error during function Testing!"
MsgBox Err.Description
End Function