I'm able to use the below code to download files from server. However, this does tell me whether the files are downloaded successfully.
Sub DownloadFirstRunFilesPart2()
Application.StatusBar = "Downloading files..."
Dim wsh As Object
Dim errorcode4 As Integer
Dim cmd5 As Variant
Dim FirstRunFiles(5) As Variant
Dim var As Variant
FirstRunFiles(0) = ProN & "_KSParameter_UserInput.xlsx"
FirstRunFiles(1) = ProN & "_KSParameter_SysOutput.xlsx"
FirstRunFiles(2) = ProN & "_ModelParameter_UserInput.xlsx"
FirstRunFiles(3) = ProN & "_ModelParameter_SysOutput.xlsx"
FirstRunFiles(4) = ProN & "_VarClusParameter_UserInput.xlsx"
FirstRunFiles(5) = ProN & "_VarClusParameter_SysOutput.xlsx"
For Each var In FirstRunFiles
cmd5 = Chr(34) & "C:\Program Files (x86)" & "\PuTTY\pscp.exe" & Chr(34) & " -sftp -l " & pUser & " -pw " & pPass & _
" " & " " & pHost & ":" & ServerPath & "/" & var & " " & LocalPath & "\"
Set wsh = CreateObject("wscript.shell")
errorcode4 = wsh.Run(cmd5, vbHide)
'If errorcode4 = 0 Then MsgBox ("Error occurs. Fail to download " & var)
Next var
Application.StatusBar = "Download complete"
MsgBox ("Downloading process complete.")
End Sub
My error code always equals 0 no matter the file exists or not. How should I change this program?
Thanks in advance!
Update:
The new code that I tried:
Sub test()
Dim wsh As Object
Dim WshShellExec As Variant
Dim cmd3 As String
Dim pFirstRunFile1 As String
Const WshFinished = 1
Const WshFailed = 2
pFirstRunFile1 = "this_proj_name.txt"
cmd3 = Chr(34) & "C:\Program Files (x86)" & "\PuTTY\pscp.exe" & Chr(34) & " -sftp -l " & pUser & " -pw " & pPass & _
" " & " " & pHost & ":" & ServerPath & "/WOE/" & pFirstRunFile1 & " " & LocalPath & "\WOE"
Set wsh = CreateObject("wscript.shell")
WshShellExec = wsh.Exec(cmd3)
Select Case WshShellExec.Status
Case WshFinished
strOutput = WshShellExec.StdOut.ReadAll
Case WshFailed
strOutput = WshShellExec.StdErr.ReadAll
End Select
MsgBox strOutput 'write results in a message box
End Sub
However I'm getting error on this line:
WshShellExec = wsh.Exec(cmd3)
The error message says "Object does not support this property or method". Any ideas?
Related
What i have so far is a Query that opens the Microsoft Access Application but i would like to open and run a sql query itself and close the application. the query like
SELECT S2iOSGISAcquisitionCSV.Agencia,
S2iOSGISAcquisitionCSV.Mercado,
S2iOSGISAcquisitionCSV.[Nome Produtor],
S2iOSGISAcquisitionCSV.Dispositivo
FROM S2iOSGISAcquisitionCSV;
where can i put that statement ? thank you
Dim sAcc
Dim sFrontEnd
Dim sSec
Dim sUser
Dim objShellDb
Dim sComTxt
Dim rs
sAcc = "C:\Program Files\Microsoft Office 15\root\office15\msaccess.exe"
'"C:\Program Files\Microsoft Office\OFFICE11\msaccess.exe"
sFrontEnd = "C:\Users\User\Desktop\TABELA_DE_DADOS.accdb"
Set objShellDb = CreateObject("WScript.Shell")
'Set rs = createObject("SELECT* FROM S2iOSGISAcquisitionCSV");
sComTxt = chr(34) & sAcc & chr(34) &_
" " & chr(34) & sFrontEnd & chr(34)
if isNull(sSec)=False AND sSec<>"" Then
sComTxt = sComTxt & " /wrkgrp " & chr(34) & sSec & chr(34)
End if
if isNull(sUser)=False AND sUser<>"" Then
sComTxt = sComTxt & " /user " & sUser
End if
objShellDb.Run sComTxt
' rs.Run sComTxt
UPDATE:
It looks like the culprit is the status reporting
ffStatus = procFFMPEG.StandardError 'Send standard error to ffStatus
strFFout = ffStatus.ReadLine 'Read every line of output and send to strFFout
It look's like it breaks the async in that part. When commented out, marquee scrollbar behave as expected.
Is there a way to be able to get those data and update status while not breaking async to show marquee progressbar?
ORIGINAL POST
I have similar problem to this question
VB.NET Marquee Progress Until Process Exits
I use the accepted answer and gets to this code
Public Async Sub GoConvert(theVCodec As String, theHeight As String)
Dim theOptions As String, theApp As String, theSourcePath As String, theDestPath As String
Dim theFilename As String, theACodec As String, theFormat As String, theLosslessOpt As String
Dim theNewFilename As String, theNewFileTag As String, theInterlaced As String, theMsg As String
Dim thePreset As String, theCRF As String
Dim ffStatus As StreamReader, strFFout As String
'On Error GoTo Handler
'SET DEFAULT VALUES
theApp = "ffmpeg.exe"
theSourcePath = txtSource.Text
theDestPath = txtOutput.Text & "\"
theACodec = "libmp3lame"
thePreset = "veryfast"
theCRF = "22"
theInterlaced = ""
theNewFileTag = ""
theLosslessOpt = ""
Select Case theVCodec
Case "libx264"
theNewFileTag = "x264"
Case "libxvid"
theNewFileTag = "xvid"
Case "libx265"
theNewFileTag = "x265"
End Select
If cmbUseCodec.Text = "x264 vegas" Then
theACodec = "aac"
theNewFileTag = "x264forVegas"
End If
theMsg = "IF FILE EXISTS, IT WILL BE OVERWRITTEN!" & vbCrLf & vbCrLf & "Please make sure that there is no filename conflict in the destination folder," & vbCrLf & "Encoder will overwrite existing files." _
& vbCrLf & vbCrLf & "Do you want to continue?"
If MessageBox.Show(theMsg, "WARNING!", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) = DialogResult.Yes Then
For i As Integer = 0 To lstSourceFiles.Items.Count - 1
If chkToFileType.CheckedItems.Count <> 0 Then
Dim x As Integer
Dim forVegas As String
For x = 0 To chkToFileType.CheckedItems.Count - 1
theFormat = chkToFileType.CheckedItems(x).ToString
'GET FILENAMES ON FILES LISTBOX
theFilename = lstSourceFiles.Items(i).ToString
theNewFilename = System.IO.Path.GetFileNameWithoutExtension(theFilename)
If chkSameOutputFolder.CheckedItems.Count > 0 Then
theDestPath = Path.GetDirectoryName(theFilename) & "\"
End If
If (theVCodec = "libx265") Then
theCRF = "28"
thePreset = "medium"
End If
If (chkLossLess.CheckedItems.Count > 0) And (theVCodec = "libx265") Then
theLosslessOpt = "-x265-params lossless=1 "
End If
If theFormat = "mp3" Then
'-i "%%a" -qa 0 - map a "%%~na.mp3"
theOptions = " -i " & Chr(34) & theFilename & Chr(34) & " -y -q:a 0 -map a " & Chr(34) & theDestPath & theNewFilename & "." & theFormat & Chr(34)
Else
'PREPARE NEW FILENAME OF CONVERTED FILE
theNewFilename = theNewFilename & "-" & theNewFileTag & "-" & theHeight & "p"
theOptions = " -i " & Chr(34) & theFilename & Chr(34) & " -y -vcodec " & theVCodec
theOptions = theOptions & " -vf " & theInterlaced & "scale=" & Chr(34) & "trunc(oh*a/2)*2:" & theHeight & Chr(34)
If cmbUseCodec.Text = "x264 vegas" Then
forVegas = " -strict experimental -tune fastdecode -pix_fmt yuv420p -b:a 192k -ar 48000"
theOptions = theOptions & " -preset " & thePreset & " -crf " & theCRF & " -acodec " & theACodec & forVegas
theOptions = theOptions & " -threads 4 " & theLosslessOpt & Chr(34) & theDestPath & theNewFilename & "." & theFormat & Chr(34)
Else
theOptions = theOptions & " -b 1750k -preset " & thePreset & " -crf " & theCRF & " -acodec " & theACodec
theOptions = theOptions & " -ac 2 -ab 160k -threads 4 " & theLosslessOpt & Chr(34) & theDestPath & theNewFilename & "." & theFormat & Chr(34)
End If
End If
theOptions = theOptions & " -loglevel error -stats"
'LET'S GET READY TO CONVERT
ConvertProcessInfo.FileName = theApp
ConvertProcessInfo.Arguments = theOptions
'LET'S TRY TO CAPTURE STATUS
ConvertProcessInfo.RedirectStandardError = True
ConvertProcessInfo.RedirectStandardOutput = True
ConvertProcessInfo.UseShellExecute = False
ConvertProcessInfo.CreateNoWindow = True
'LET'S PROVIDE SOME MEANINGFUL INFO
procFFMPEG.StartInfo = ConvertProcessInfo
lstStatus.Items(i) = "Encoding: " & theFormat
txtProcessInfo.Text = "Encoding file: " & theNewFilename & "." & theFormat
'LET'S DISABLE CONTROLS WHILE CONVERT IS WORKING AND ENABLE PROGRESSBAR
prgrssConvert.Visible = True
DisableControls()
'LET'S CONVERT
procFFMPEG.Start()
Do
Application.DoEvents()
ffStatus = procFFMPEG.StandardError 'Send standard error to ffStatus
strFFout = ffStatus.ReadLine 'Read every line of output and send to strFFout
Debug.Print(strFFout)
txtProcessInfo.Text = strFFout
'THESE LINES IS NOT NEEDED IF ASYNC WILL WORK
txtProcessInfo.Refresh()
lstSourceFiles.Refresh()
lstStatus.Refresh()
prgrssConvert.Refresh()
Loop Until procFFMPEG.HasExited
'LET'S WAIT FOR PROCESS TO EXIT
Await Task.Run(Sub() procFFMPEG.WaitForExit())
'UPDATE STATUS AFTER EVERY FILE
prgrssConvert.Visible = False
lstStatus.Items(i) = "DONE"
Next
End If
Next
'WHEN ALL FILES DONE, UPDATE STATUS
txtProcessInfo.Text = "Encoding completed. Waiting for new task"
EnableControls()
End If
End Sub
My problem is that the progressbar (prgrssConvert.Visible = True) is not updating asynchronously that is why I have to add refresh in the DO LOOP but it is not that visually appealing because it is "robotic" and not smoothly flowing marquee.
It looks to me that async is not doing it's job. I am hoping to keep the progressbar marquee running while waiting for the ffmpeg process to complete.
Any idea why async is not working on my code?
Thanks
There perfect answer for a good questions. I didn't see you were returning the output to a textbox. sorry. You have to use readlineasync otherwise your are waiting for a line from your output that might only come at the end. If it never comes your app will be stuck there.
This is for reading errors procFFMPEG.StandardError
If you actually want the output of your process use this
procMMFPEG.StandardOutput instead or both but you will need to adapt your code to it
some reference for StandardOutput
Public Async Sub GoConvert(theVCodec As String, theHeight As String)
Dim theOptions As String, theApp As String, theSourcePath As String, theDestPath As String
Dim theFilename As String, theACodec As String, theFormat As String, theLosslessOpt As String
Dim theNewFilename As String, theNewFileTag As String, theInterlaced As String, theMsg As String
Dim thePreset As String, theCRF As String
Dim ffStatus As StreamReader, strFFout As String
'On Error GoTo Handler
'SET DEFAULT VALUES
theApp = "ffmpeg.exe"
theSourcePath = txtSource.Text
theDestPath = txtOutput.Text & "\"
theACodec = "libmp3lame"
thePreset = "veryfast"
theCRF = "22"
theInterlaced = ""
theNewFileTag = ""
theLosslessOpt = ""
Select Case theVCodec
Case "libx264"
theNewFileTag = "x264"
Case "libxvid"
theNewFileTag = "xvid"
Case "libx265"
theNewFileTag = "x265"
End Select
If cmbUseCodec.Text = "x264 vegas" Then
theACodec = "aac"
theNewFileTag = "x264forVegas"
End If
theMsg = "IF FILE EXISTS, IT WILL BE OVERWRITTEN!" & vbCrLf & vbCrLf & "Please make sure that there is no filename conflict in the destination folder," & vbCrLf & "Encoder will overwrite existing files." _
& vbCrLf & vbCrLf & "Do you want to continue?"
If MessageBox.Show(theMsg, "WARNING!", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) = DialogResult.Yes Then
'LET'S DISABLE CONTROLS WHILE CONVERT IS WORKING AND ENABLE PROGRESSBAR
prgrssConvert.Visible = True
DisableControls()
prgrssConvert.value = 0 'I assumed this was a progressbar
prgrssConvert.maximum = lstSourceFiles.Items.Count * chkToFileType.CheckedItems.Count
For i As Integer = 0 To lstSourceFiles.Items.Count - 1
If chkToFileType.CheckedItems.Count <> 0 Then
Dim x As Integer
Dim forVegas As String
For x = 0 To chkToFileType.CheckedItems.Count - 1
theFormat = chkToFileType.CheckedItems(x).ToString
'GET FILENAMES ON FILES LISTBOX
theFilename = lstSourceFiles.Items(i).ToString
theNewFilename = System.IO.Path.GetFileNameWithoutExtension(theFilename)
If chkSameOutputFolder.CheckedItems.Count > 0 Then
theDestPath = Path.GetDirectoryName(theFilename) & "\"
End If
If (theVCodec = "libx265") Then
theCRF = "28"
thePreset = "medium"
End If
If (chkLossLess.CheckedItems.Count > 0) And (theVCodec = "libx265") Then
theLosslessOpt = "-x265-params lossless=1 "
End If
If theFormat = "mp3" Then
'-i "%%a" -qa 0 - map a "%%~na.mp3"
theOptions = " -i " & Chr(34) & theFilename & Chr(34) & " -y -q:a 0 -map a " & Chr(34) & theDestPath & theNewFilename & "." & theFormat & Chr(34)
Else
'PREPARE NEW FILENAME OF CONVERTED FILE
theNewFilename = theNewFilename & "-" & theNewFileTag & "-" & theHeight & "p"
theOptions = " -i " & Chr(34) & theFilename & Chr(34) & " -y -vcodec " & theVCodec
theOptions = theOptions & " -vf " & theInterlaced & "scale=" & Chr(34) & "trunc(oh*a/2)*2:" & theHeight & Chr(34)
If cmbUseCodec.Text = "x264 vegas" Then
forVegas = " -strict experimental -tune fastdecode -pix_fmt yuv420p -b:a 192k -ar 48000"
theOptions = theOptions & " -preset " & thePreset & " -crf " & theCRF & " -acodec " & theACodec & forVegas
theOptions = theOptions & " -threads 4 " & theLosslessOpt & Chr(34) & theDestPath & theNewFilename & "." & theFormat & Chr(34)
Else
theOptions = theOptions & " -b 1750k -preset " & thePreset & " -crf " & theCRF & " -acodec " & theACodec
theOptions = theOptions & " -ac 2 -ab 160k -threads 4 " & theLosslessOpt & Chr(34) & theDestPath & theNewFilename & "." & theFormat & Chr(34)
End If
End If
theOptions = theOptions & " -loglevel error -stats"
'LET'S GET READY TO CONVERT
ConvertProcessInfo.FileName = theApp
ConvertProcessInfo.Arguments = theOptions
'LET'S TRY TO CAPTURE STATUS
ConvertProcessInfo.RedirectStandardError = True
ConvertProcessInfo.RedirectStandardOutput = True
ConvertProcessInfo.UseShellExecute = False
ConvertProcessInfo.CreateNoWindow = True
'LET'S PROVIDE SOME MEANINGFUL INFO
procFFMPEG.StartInfo = ConvertProcessInfo
lstStatus.Items(i) = "Encoding: " & theFormat
txtProcessInfo.Text = "Encoding file: " & theNewFilename & "." & theFormat
'LET'S CONVERT
procFFMPEG.Start()
Do
ffStatus = procFFMPEG.StandardError 'Send standard error to ffStatus
strFFout = Await(ffStatus.ReadLineAsync()) 'Read every line of output and send to strFFout
Debug.Print(strFFout)
txtProcessInfo.Text = strFFout
Loop Until procFFMPEG.HasExited = True
'UPDATE STATUS AFTER EVERY FILE
prgrssConvert.value += 1
Next
lstStatus.Items(i) = "DONE"
End If
Next
prgrssConvert.Visible = False
'WHEN ALL FILES DONE, UPDATE STATUS
txtProcessInfo.Text = "Encoding completed. Waiting for new task"
EnableControls()
End If
End Sub
This is untested, but can you try this:
Do
Await Task.Delay(TimeSpan.FromSeconds(0.1))
ffStatus = procFFMPEG.StandardError 'Send standard error to ffStatus
strFFout = ffStatus.ReadLine 'Read every line of output and send to strFFout
Debug.Print(strFFout)
txtProcessInfo.Text = strFFout
Loop Until Await Task.Run(Function() procFFMPEG.HasExited)
Here's a simple bit of code to test that this works:
Dim process As New Process()
process.StartInfo = New ProcessStartInfo("C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe")
process.Start()
Do
Await Task.Delay(TimeSpan.FromSeconds(0.1))
Console.WriteLine("!")
Loop Until Await Task.Run(Function() process.HasExited)
It produces lines of ! until the PowerShell console is closed.
I am trying to call a .bat file from VBA using: however I am getting Method Run of object IWshShell3 failed with the line in asteriks highlighted. I am not familiar with this error and don't know where to begin. I am running VB in excel 2010. Thank you :).
Dim PathCrnt As String
Dim wsh As Object
PathCrnt = ActiveWorkbook.Path & "\" & MyBarCode & "_" & MyScan
Set wsh = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1
**wsh.Run "C:\Users\cmccabe\Desktop\NxClinical.bat", windowStyle, waitOnReturn**
End If
EDIT
The code runs but exits with error code 1. Basically, what I am trying to do is have the user enter a barcode and date, those values are used to change the directory to that. A batch file is called that runs a perl script on that directory. The batch file is not being called and I'm not sure why. Thank you :).
VBA
Private Sub CommandButton3_Click()
Dim MyBarCode As String ' Enter Barcode
Dim MyScan As String ' Enter ScanDate
Dim MyDirectory As String
MyBarCode = Application.InputBox("Please enter the barcode", "Bar Code", Type:=2)
If MyBarCode = "False" Then Exit Sub 'user canceled
Do
MyScan = Application.InputBox("Please enter scan date", "Scan Date", Date, Type:=2)
If MyScan = "False" Then Exit Sub 'user canceled
If IsDate(MyScan) Then Exit Do
MsgBox "Please enter a valid date format. ", vbExclamation, "Invalid Date Entry"
Loop
Range("B20").Value = MyBarCode
Range("B21").Value = CDate(MyScan)
MyDirectory = "N:\1_DATA\MicroArray\NexusData\" & MyBarCode & "_" & Format(CDate(MyScan), "m-d-yyyy") & "\"
' Create nexus directory and folder
If Dir(MyDirectory, vbDirectory) = "" Then MkDir MyDirectory
If MsgBox("The project file has been created. " & _
"Do you want to create a template for analysis now?", _
vbQuestion + vbYesNo) = vbYes Then
'Write to text file
Open MyDirectory & "sample_descriptor.txt" For Output As #1
Print #1, "Experiment Sample" & vbTab & "Control Sample" & vbTab & "Display Name" & vbTab & "Gender" & vbTab & "Control Gender" & vbTab & "Spikein" & vbTab & "SpikeIn Location" & vbTab & "Barcode"
Print #1, MyBarCode & "_532Block1.txt" & vbTab & MyBarCode & "_635Block1.txt" & vbTab & ActiveSheet.Range("B8").Value & " " & ActiveSheet.Range("B9").Value & vbTab & ActiveSheet.Range("B10").Value & vbTab & ActiveSheet.Range("B5").Value & vbTab & ActiveSheet.Range("B11").Value & vbTab & ActiveSheet.Range("B12").Value & vbTab & ActiveSheet.Range("B20").Value
Print #1, MyBarCode & "_532Block2.txt" & vbTab & MyBarCode & "_635Block2.txt" & vbTab & ActiveSheet.Range("C8").Value & " " & ActiveSheet.Range("C9").Value & vbTab & ActiveSheet.Range("C10").Value & vbTab & ActiveSheet.Range("C5").Value & vbTab & ActiveSheet.Range("C11").Value & vbTab & ActiveSheet.Range("C12").Value & vbTab & ActiveSheet.Range("B20").Value
Print #1, MyBarCode & "_532Block3.txt" & vbTab & MyBarCode & "_635Block3.txt" & vbTab & ActiveSheet.Range("D8").Value & " " & ActiveSheet.Range("D9").Value & vbTab & ActiveSheet.Range("D10").Value & vbTab & ActiveSheet.Range("D5").Value & vbTab & ActiveSheet.Range("D11").Value & vbTab & ActiveSheet.Range("D12").Value & vbTab & ActiveSheet.Range("B20").Value
Print #1, MyBarCode & "_532Block4.txt" & vbTab & MyBarCode & "_635Block4.txt" & vbTab & ActiveSheet.Range("E8").Value & " " & ActiveSheet.Range("E9").Value & vbTab & ActiveSheet.Range("E10").Value & vbTab & ActiveSheet.Range("E5").Value & vbTab & ActiveSheet.Range("E11").Value & vbTab & ActiveSheet.Range("E12").Value & vbTab & ActiveSheet.Range("B20").Value
Close #1
'Run ImaGene
If MsgBox("Please run the ImaGene analysis. " & _
"and click yes after it completes to verify the spike-ins.", _
vbQuestion + vbYesNo) = vbYes Then
'Update folder structure and call perl
Dim PathCrnt As String
Dim Wsh As Object
Dim WaitOnReturn As Boolean
Dim WindowStyle As Integer
PathCrnt = MyDirectory
Set Wsh = VBA.CreateObject("WScript.Shell")
WaitOnReturn = True
WindowStyle = 1
Wsh.Run PathCrnt & "C:\Users\cmccabe\Desktop\NxClinical.bat", WindowStyle, WaitOnReturn
End If
Else
MsgBox "Nothing has been done. ", vbExclamation, "Goodbye!"
End If
Application.DisplayAlerts = False
Application.Quit
End Sub
Dim PathCrnt As String
Dim wsh As Object
PathCrnt = ActiveWorkbook.Path & "\" & MyBarCode & "_" & MyScan
Set wsh = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1
Dim errrCode As Long
errrCode = wsh.Run( "cmd /C ""C:\Users\cmccabe\Desktop\NxClinical.bat""" _
, windowStyle, waitOnReturn)
If errrCode = 0 Then
MsgBox "Done! No error to report."
Else
MsgBox "Program exited with error code " & errrCode & "."
End If
Note
explicitly run cmd /c;
enclose batch script (fully qualified) name in double quotes;
get (and treat) errrCode from called batch script.
If your batch script requires paramer(s), use them as follows (an example):
errrCode = wsh.Run( "cmd /C ""C:\Users\cmccabe\Desktop\NxClinical.bat"" par1 ""par 2""" _
, windowStyle, waitOnReturn)
Another example:
errrCode = wsh.Run( "cmd /C ""C:\Users\cmccabe\Desktop\NxClinical.bat"" " _
_ & """" & PathCrnt & """" , windowStyle, waitOnReturn)
I am working on VBA, from which I have to call a vbscript by passing some values.
Here is the code:
''VBA
'Below values are on different cells of Excel file which I am reading
'into a global variable then pass it to vbscript.
'SFilename = VBscript file path
'QClogin = "abc"
'QCpassword = "abc"
'sDomain = "xyz"
'sProject = "xyz123"
'testPathALM = "Subject\xyz - Use it!\xyz_abc"
'QCurl = "http://xxx_yyy_zzz/qcbin/"
Set wshShell = CreateObject("Wscript.Shell")
Set proc = wshShell.exec("wscript " & SFilename & " " & QClogin & _
" " & "" & QCpassword & " " & "" & sDomain & " " & "" & sProject & _
" " & "" & testPathALM & " " & "" & QCurl & "")
''VBscript on some location
Dim strUserName, strPassword, strServer
strUserName = WScript.Arguments(0) '"abc"
Msgbox "strUserName : " & strUserName
strPassword = WScript.Arguments(1) '"abc"
Msgbox "strPassword : " & strPassword
strServer = WScript.Arguments(5) '"http://xxx_yyy_zzz/qcbin/"
Msgbox "strServer : " & strServer
Dim strDomain, strProject, strRootNode
strDomain = WScript.Arguments(2) '"xyz"
Msgbox "strDomain: " & strDomain
strProject = WScript.Arguments(3) '"xyz123"
Msgbox "strProject: " & strProject
strRootNode = WScript.Arguments(4) '"Subject\xyz - Use it!\xyz_abc"
Msgbox "strRootNode: " & strRootNode
Now, when I running the code, it is passing below values properly to vbscript:
QClogin = "abc"
QCpassword = "abc"
sDomain = "xyz"
sProject = "xyz123"
It is having issues with these:
testPathALM = "Subject\xyz - Use it!\xyz_abc"
QCurl = "http://xxx_yyy_zzz/qcbin/"
Now, wierd thing for me is, if I keep a cell empty for "testPathALM" which is having "Subject\xyz - Use it!\xyz_abc" as value, I am getting "QCurl" value properly in vbscript.
But, if I keep value "Subject\xyz - Use it!\xyz_abc" for "testPathALM", then I am getting "-" for strServer which suppose to be "QCurl" value and "Subject\xyz" for "strRootNode" which supposed to be "Subject\xyz - Use it!\xyz_abc".
I am unable to understand what is the issue here.
Thanks a ton in advance.
Safer to quote all of your parameters:
Set wshShell = CreateObject("Wscript.Shell")
Set proc = wshShell.exec("wscript """ & SFilename & """ """ & _
QClogin & """ """ & QCpassword & """ """ & _
sDomain & """ """ & sProject & """ """ & _
testPathALM & """ """ & QCurl & """")
Try a debug.print to make sure it looks as it should...
I have the following code to monitor a drive. Now I an getting Echo for each file creation or deletion event.
Is there and way to modify the WScript.Echo to send a mail notification?
strDrive = "c"
arrFolders(0) = strDrive & "\\\\"
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2")
'Loop throught the array of folders setting up the monitor for Each
i = 0
For Each strFolder In arrFolders
'Create the event sink
strCommand = "Set EventSink" & i & " = WScript.CreateObject" & "(""WbemScripting.SWbemSink"", ""SINK" & i & "_"")"
ExecuteGlobal strCommand
'Setup Notification
strQuery = "SELECT * FROM __InstanceOperationEvent WITHIN 1 " & "WHERE Targetinstance ISA 'CIM_DirectoryContainsFile'" & " and TargetInstance.GroupComponent = " & "'Win32_Directory.Name=""" & strFolder & """'"
strCommand = "objWMIservice.ExecNotificationQueryAsync EventSink" & i & ", strQuery"
ExecuteGlobal strCommand
'Create the OnObjectReady Sub
strCommand = "Sub SINK" & i & "_OnObjectReady(objObject, " & "objAsyncContext)" & VbCrLf & vbTab & "Wscript.Echo objObject.TargetInstance.PartComponent" & VbCrLf & "End Sub"
WScript.Echo strCommand
ExecuteGlobal strCommand
i = i + 1
Next
WScript.Echo "Waiting for events..."
i = 0
While (True)
Wscript.Sleep(1000)
Wend
Instead of Echoing like below:
strCommand = "Sub SINK" & i & "_OnObjectReady(objObject, " & "objAsyncContext)" & VbCrLf & vbTab & "Wscript.Echo objObject.TargetInstance.PartComponent" & VbCrLf & "End Sub"
I want to send a mail like this:
strCommand = "Sub SINK" & i & "_OnObjectReady(objObject, " & "objAsyncContext)" & VbCrLf & vbTab & "
Set outobj = CreateObject("Outlook.Application")
Set mailobj = outobj.CreateItem(0)
With mailobj
.To = toAddress
.Subject = Subject
.HTMLBody = strHTML
.Send
End With
" & VbCrLf & "End Sub"
Is it possible or is there an other way to do this..?
I don't know what server do you use, but on Windows 2003 and 2008 e.g. you can use CDO object to create a email. You might use a smart host to send your email to.
Check this link: http://www.paulsadowski.com/wsh/cdo.htm
Also you can choose any free email component to create a email and use a smtp server to send your email. Or check this side where you can use a component including many examples how to do it: http://www.chilkatsoft.com/email-activex.asp.
** UPDATED **
This Script checks and send a email as you requestted:
strDrive = "d:"
Dim arrFolders(0) : arrFolders(0) = strDrive & "\\\\"
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2")
'Loop throught the array of folders setting up the monitor for Each
i = 0
For Each strFolder In arrFolders
'Create the event sink
WScript.Echo "setup for folder: " & strFolder & vbLf
strCommand = "Set EventSink" & i & " = WScript.CreateObject" & "(""WbemScripting.SWbemSink"", ""SINK" & i & "_"")"
ExecuteGlobal strCommand
'Setup Notification
strQuery = "SELECT * " _
& "FROM __InstanceOperationEvent " _
& "WITHIN 1 " _
& "WHERE Targetinstance ISA 'CIM_DirectoryContainsFile'" _
& " AND TargetInstance.GroupComponent = " & "'Win32_Directory.Name=""" & strFolder & """'"
strCommand = "objWMIservice.ExecNotificationQueryAsync EventSink" & i & ", strQuery"
ExecuteGlobal strCommand
'Create the OnObjectReady Sub
strCommand = "Sub SINK" & i & "_OnObjectReady(objObject, " & "objAsyncContext)" & vbLf _
& " Wscript.Echo objObject.TargetInstance.PartComponent" & vbLf _
& " SendMail(objObject.TargetInstance.PartComponent)" & vbLf _
& "End Sub"
'WScript.Echo strCommand
ExecuteGlobal strCommand
i = i + 1
Next
WScript.Echo "Waiting for events..."
i = 0
While (True)
Wscript.Sleep(1000)
Wend
Function SendMail(vBody)
Dim oMail : Set oMail = CreateObject("CDO.Message")
'Name or IP of Remote SMTP Server
oMail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
oMail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "your.smtp.server"
oMail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
oMail.Configuration.Fields.Update
oMail.Subject = "Email Watch Info Message"
oMail.From = "alert#yourdomain.net"
oMail.To = "target#yourdomain.net"
oMail.TextBody = vBody
oMail.Send
End Function
Correct the settings in the send mail function and your are fine.
In theory, the VBSendMail DLL should be able to do what you want.