Every time I need to grant user access to a file share on our server, I get numerous occurrences of this popup because the process hits various files whose access rights I can't modify:
This isn't a problem, but I got tired of having to repeatedly stop what I was working on to click on the "Continue" button. So, I wrote a program to continually scan for an "Error Applying Security" window, and whenever it found one, send it an "Enter" keypress. This worked well enough, but since the central loop never terminates, I decided to add the ability to end the program when it was finished. I could have used an .hta file, but I decided to try a different approach that kept everything in a single file to make future maintenance easier. I adopted the code from this Stack Overflow question to find my program's PID and allow the program to be ended using the Windows TASKKILL command after a popup was closed.
The program seems to work correctly, identifying its PID and passing it to the popup. However, when TASKKILL runs, it claims the PID doesn't exist. Can anyone see what I'm doing wrong? Thanks in advance to all who respond.
' AutoContinue.vbs
' Program to automatically close all "Error Applying Security" messages
Option Explicit
Const Hidden = 0
Dim objWshShell, objWMILocator, objWMIService
Dim strComputerName, objArgs, objChildProcess, colPIDs, objPID
Set objWshShell = CreateObject( "WScript.Shell" )
Set objWMILocator = CreateObject( "WBemScripting.SWbemLocator" )
Set objWMIService = objWMILocator.ConnectServer( "", "", "", "" )
Function MyProcessID ()
' MyProcessID finds and returns my own PID.
MyProcessID = 0
Set objChildProcess = objWshShell.Exec( "%comspec% /C pause" )
Set colPIDs= objWMIService.ExecQuery( "Select * From Win32_Process" & _
" Where ProcessId=" & objChildProcess.ProcessID,, 0 )
For Each objPID In colPIDs
MyProcessID = objPID.ParentProcessID
Next
Call objChildProcess.Terminate()
End Function
Set objArgs = WScript.Arguments
If objArgs.Count = 1 Then
If objArgs.Item(0) = "Popup" Then
objWshShell.Popup( "AutoContinue PID is " & MyProcessID & _
vbCrLf & "Hit OK when done." )
' objWshShell.Run "taskkill /PID " & MyProcessID & " /T", 1
objWshShell.Run "%comspec% /k taskkill /PID " & MyProcessID & " /T", 1
Set objArgs = Nothing
Set objWshShell = Nothing
WScript.Quit
End If
End If
objWshShell.Run "wscript.exe " & WScript.ScriptName & " Popup", Hidden
Do
Do
WScript.Sleep( 500 )
Loop While Not objWshShell.AppActivate( "Error Applying Security" )
WScript.Sleep( 100 )
objWshShell.AppActivate( "Error Applying Security" )
WScript.Sleep( 100 )
objWshShell.SendKeys( "{ENTER}" )
Loop While True
Set objWshShell = Nothing
The script identifies its own PID correctly. However, you are trying to kill itself (the script instance with supplied Popup argument) while you need to kill the script instance without it (or with another 1st argument?).
The following solution could help: supply PID of the instance to kill as 2nd argument (see variable iPid) along with the Popup one…
' AutoContinue.vbs
' Program to automatically close all "Error Applying Security" messages
Option Explicit
Const Hidden = 0
Dim objWshShell, objWMILocator, objWMIService
Dim strComputerName, objArgs, objChildProcess, colPIDs, objPID
Set objWshShell = CreateObject( "WScript.Shell" )
Set objWMILocator = CreateObject( "WBemScripting.SWbemLocator" )
Set objWMIService = objWMILocator.ConnectServer( "", "", "", "" )
Function MyProcessID ()
' MyProcessID finds and returns my own PID.
MyProcessID = 0
Set objChildProcess = objWshShell.Exec( "%comspec% /C pause" )
Set colPIDs= objWMIService.ExecQuery( "Select * From Win32_Process" & _
" Where ProcessId=" & objChildProcess.ProcessID,, 0 )
For Each objPID In colPIDs
MyProcessID = objPID.ParentProcessID
Next
Call objChildProcess.Terminate()
End Function
Dim iPid
iPid = MyProcessID()
Set objArgs = WScript.Arguments
If objArgs.Count >= 2 Then
If objArgs.Item(0) = "Popup" Then
objWshShell.Popup( "AutoContinue PID is " & objArgs.Item(1) & _
vbCrLf & "Hit OK when done." )
' objWshShell.Run "taskkill /PID " & objArgs.Item(1) & " /T /F", 1
objWshShell.Run "%comspec% /k taskkill /PID " & objArgs.Item(1) & " /T /F", 1
Set objArgs = Nothing
Set objWshShell = Nothing
WScript.Quit
End If
End If
objWshShell.Run "wscript.exe """ _
& WScript.ScriptFullName & """ Popup " & CStr( iPid) , Hidden
'' ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ two arguments
Do
Do
WScript.Sleep( 500 )
Loop While Not objWshShell.AppActivate( "Error Applying Security" )
WScript.Sleep( 100 )
objWshShell.AppActivate( "Error Applying Security" )
WScript.Sleep( 100 )
objWshShell.SendKeys( "{ENTER}" )
Loop While True
Related
Here or there I have found Cleanmgr.exe and Ccleaner to hang. When they do, typically the CPU usage is upwards of 90%+. The hangs are intermittent and hard to reproduce, but when they hang, task manager has reported running them running for over 8 hours. 99% CPU usage is typical for a few seconds.
So I wrote a short little vbScript to run the apps, then kill it if it takes too long - I'm thinking no more than 3 minutes per app. FYI, I'm running out of box, from WinXp to 8.1, so I really only have vbScript and the command line.
First attempt appeared successful, but then I found I had to apply a second test, again with another timer, however, now I find my script doesn't exit at all when Cleanmgr or CCleaner hangs.
This started simple, and now it's nuts. I'm hoping someone out here can help me. I think the issue is, the process is chewing up my CPU, so the timer check in my script can't run...
It occurred to me, I'm calling this from a cmd file using cScript - could there be some issue there?
Is there a way to track the process time rather than from a timer? Create a thread higher priority than the process so it can terminate when it hangs? Maybe I have bug in my code? Help please, I'm going nuts. Thank you.
Option Explicit
On Error Goto 0
Dim wshShell, sysPath, waitTime, i, str, masterTimer, mElapsed, slp
Dim apps(), paths(), params()
Set wshShell=WScript.CreateObject("wScript.Shell")
sysPath = wshShell.ExpandEnvironmentStrings("%SystemRoot%")
waitTime = 90
slp = 2255
ReDim apps(2)
ReDim paths(2)
ReDim params(2)
apps(0) = "cleanmgr.exe"
paths(0) = sysPath&"\System32"
params(0) = "/SageRun:101"
apps(1) = "ccleaner.exe"
paths(1) = "C:\Program Files\ccleaner"
params(1) = "/AUTO"
apps(2) = "ccleaner64.exe"
paths(2) = "C:\Program Files\ccleaner"
params(2) = "/AUTO"
For i=LBound(apps) to UBound(apps)
str="cmd.exe /C taskkill.exe /im " & apps( i ) & " /f /t"
wshShell.run str
str="cmd.exe /C taskkill.exe /im " & apps( i ) & " /f"
wshShell.run str
str="cmd.exe /C tskill.exe " & apps( i ) & " /a /v"
wshShell.run str
WScript.Sleep slp
masterTimer = Timer
mElapsed = 0
RunCleaner paths(i),apps(i),params(i)
str="cmd.exe /C taskkill.exe /im " & apps( i ) & " /f /t"
wshShell.run str
str="cmd.exe /C taskkill.exe /im " & apps( i ) & " /f"
wshShell.run str
str="cmd.exe /C tskill.exe " & apps( i ) & " /a /v"
wshShell.run str
Set Str=Nothing
Wscript.sleep slp
Next
ReDim apps(0)
ReDim paths(0)
ReDim params(0)
Erase apps
Erase paths
Erase params
Set slp=Nothing
Set sysPath=Nothing
Set wshShell=Nothing
Set waitTime=Nothing
WScript.Quit(0)
Public Sub RunCleaner( strPath, prog, args )
Dim objFSO, objWMIService, objProcess, objStartup, objConfig, colMonitoredProcesses, objLatestProcess
Dim intProcessID, erReturn, processes, proc
Dim fullPath, elapsed, startTime, running
Set objFSO=CreateObject( "Scripting.FileSystemObject" )
fullPath = "" & strpath & "\" & prog
If objFSO.FileExists( fullPath ) Then
Set objWMIService= GetObject( "winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2" )
Set objProcess = GetObject( "winmgmts:root\cimv2:Win32_Process" )
Set objStartup = objWMIService.Get( "Win32_ProcessStartup" )
Set objConfig = objStartup.SpawnInstance_
objConfig.ShowWindow = 1
elapsed = -1 * slp
startTime = Timer
Wscript.sleep slp
erReturn = objProcess.Create ( fullPath & " " & args, Null, objConfig, intProcessID )
Set colMonitoredProcesses = objWMIService. _
ExecNotificationQuery( "select * From __InstanceDeletionEvent " _
& " within 1 where TargetInstance isa 'Win32_Process'" )
Do While ( ( elapsed < waitTime ) And ( ( mElapsed ) < waitTime ) )
Set objLatestProcess = colMonitoredProcesses.NextEvent
If objLatestProcess.TargetInstance.ProcessID = intProcessID Then
Exit Do
End If
elapsed = Timer - startTime
mElapsed = Timer - masterTimer
Loop
WScript.sleep slp
running = True
Do While ( ( running ) And ( elapsed < waitTime ) And ( mElapsed < waitTime ) )
SET processes = GetObject( "winmgmts:" )
running = False
elapsed = ( Timer - startTime ) / 2
For Each proc in processes.InstancesOf( "Win32_Process" )
If ( StrComp( LCase( proc.Name ), LCase( prog ), vbTextCompare ) = 0 ) Then
running = True
Exit For
End If
Next
Set processes=Nothing
mElapsed = ( Timer - masterTimer ) / 2
Loop
WScript.sleep slp
fullPath = "cmd.exe /C taskkill.exe /im " & prog & " /f /t"
wshShell.run fullPath
fullPath = "cmd.exe /C taskkill.exe /im " & prog & " /f"
wshShell.run fullPath
fullPath = "cmd.exe /C tskill.exe " & prog & " /a /v"
wshShell.run fullPath
Set objWMIService=Nothing
Set objProcess=Nothing
Set objStartup=Nothing
Set objConfig=Nothing
Set objProcess=Nothing
Set erReturn=Nothing
Set intProcessID=Nothing
Set colMonitoredProcesses=Nothing
Set elapsed=Nothing
Set startTime=Nothing
Set objLatestProcess=Nothing
Set running=Nothing-1 * slp
Set proc=Nothing
Set fullPath=Nothing
End If
Set objFSO=Nothing
End Sub
Your script seems a bit complex for what it needs to do. Try this out.
The exes are executed consecutively. If any are running for longer than 3 minutes then they're terminated via taskkill. If you want to do away with WMI queries altogether (which is probably where your script is having to fight for CPU) you could simply wait three minutes for each exe you start and then send a taskkill without checking whether it's still running. You could also do a tasklist rather than a WMI query.
Dim fso, shl, wmi
Set fso = CreateObject("Scripting.FileSystemObject")
Set shl = CreateObject("WScript.Shell")
Set wmi = GetObject("winmgmts:\\.\root\cimv2")
Dim app1, app2, app3, apps()
ReDim apps(-1)
app1 = fso.BuildPath(shl.ExpandEnvironmentStrings("%SYSTEMROOT%"), "System32\cleanmgr.exe")
app2 = "C:\Program Files\ccleaner\ccleaner.exe"
app3 = "C:\Program Files\ccleaner\ccleaner64.exe"
If fso.FileExists(app1) Then AddApp app1, "/SageRun:101"
If fso.FileExists(app2) Then AddApp app2, "/AUTO"
If fso.FileExists(app3) Then AddApp app3, "/AUTO"
If UBound(apps) < 0 Then WScript.Quit ' None of the programs exist
Dim apptorun, starttime, running, process
For Each apptorun In apps
starttime = Now
process = fso.GetFile(apptorun.exe).Name
shl.Run apptorun.exe & " " & apptorun.param, 0, False
Do While 1
WScript.Sleep 5000
Set running = wmi.ExecQuery("select * from win32_process where name = """ & process & """")
If running.Count = 0 Then Exit Do
If DateDiff("n", starttime, Now) > 3 Then
shl.Run "taskkill /f /im " & process, 0, True
Exit Do
End If
Loop
Next
Sub AddApp(app, arg)
ReDim Preserve apps(UBound(apps) + 1)
Set apps(UBound(apps)) = New program
apps(UBound(apps)).exe = app
apps(UBound(apps)).param = arg
End Sub
Class program
Dim exe, param
End Class
I use this snippet in vbscript:
Set WSH = CreateObject("WScript.Shell")
cmd = "some command"
flag = WSH.Run(cmd, 0, true)
As it can be noticed, in .Run() call, "WaitOnReturn" is set to "true" as I want to know when external program finishes and additionally it status
Problem is that external program needs some time to finish and I want to pop "Please wait..." MsgBox but I can't this way as I set "WaitOnReturn" on "true" which I need as I need result from that program for additional processing
Is there a way I can show somehow this MsgBox while external program is executed?
Sorry, it slipped to me that i can call MsgBox just before executing, Run()
:embarrassed:
Edit:
for no user interaction here is one workaround (taken from http://www.robvanderwoude.com/vbstech_ui_progress.php)
Function ProgressMsg( strMessage, strWindowTitle )
' Written by Denis St-Pierre
Set wshShell = WScript.CreateObject( "WScript.Shell" )
strTEMP = wshShell.ExpandEnvironmentStrings( "%TEMP%" )
If strMessage = "" Then
On Error Resume Next
objProgressMsg.Terminate( )
On Error Goto 0
Exit Function
End If
Set objFSO = CreateObject("Scripting.FileSystemObject")
strTempVBS = strTEMP + "\" & "Message.vbs"
Set objTempMessage = objFSO.CreateTextFile( strTempVBS, True )
objTempMessage.WriteLine( "MsgBox""" & strMessage & """, 4096, """ & strWindowTitle & """" )
objTempMessage.Close
On Error Resume Next
objProgressMsg.Terminate( )
On Error Goto 0
Set objProgressMsg = WshShell.Exec( "%windir%\system32\wscript.exe " & strTempVBS )
Set wshShell = Nothing
Set objFSO = Nothing
End Function
Then call it with:
ProgressMsg "Installing, Please wait.", "Some title"
end terminate it with:
ProgressMsg "", "Some title"
I was given an answer on another blog, basically, all I had to do was dim the variable "ProgressMsg" globally.
Thanks
I'm using the following code snippet to determine what process ID my vbscript is running as:
On Error Resume Next
Dim iMyPID : iMyPID = GetObject("winmgmts:root\cimv2").Get("Win32_Process.Handle='" & CreateObject("WScript.Shell").Exec("mshta.exe").ProcessID & "'").ParentProcessId
If Err.Number <> 0 Then Call Handle_Error(Err.Description)
On Error Goto 0
On my Windows 7 (32-bit) machine this works about 90% of the time and iMyPID contains the process ID of the currently running script. However 10% of the time Handle_Error gets called with the error message "SWbemServicesEX: Not found".
Recently someone else running Windows 7 (64-bit) reported that Handle_Error always gets called with the error message "Out of memory". This seems an insane error message just to find out your own process ID!
Can anyone recommend a better way of doing this?
mshta terminates itself immediately. Maybe it's too late to achieve parent process id by using WMI service.
So, I'd use something like this to eliminate concurrent script processes.
Generate random things.
Determine an application which could be installed on each system, never terminates by itself (e.g. command prompt with /k parameter).
Start the application in hidden mode with generated random argument (WshShell.Run).
Wait a few milliseconds
Query the running processes by using command line argument value.
Get the ParentProcessId property.
Function CurrProcessId
Dim oShell, sCmd, oWMI, oChldPrcs, oCols, lOut
lOut = 0
Set oShell = CreateObject("WScript.Shell")
Set oWMI = GetObject(_
"winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
sCmd = "/K " & Left(CreateObject("Scriptlet.TypeLib").Guid, 38)
oShell.Run "%comspec% " & sCmd, 0
WScript.Sleep 100 'For healthier skin, get some sleep
Set oChldPrcs = oWMI.ExecQuery(_
"Select * From Win32_Process Where CommandLine Like '%" & sCmd & "'",,32)
For Each oCols In oChldPrcs
lOut = oCols.ParentProcessId 'get parent
oCols.Terminate 'process terminated
Exit For
Next
CurrProcessId = lOut
End Function
Dim ProcessId
ProcessId = CurrProcessId 'will remain valid indefinitely
WScript.Echo ProcessId
Here's an even better code snippet:
' ***********************************************************************************************************
' lng_MyProcessID finds and returns my own process ID. This is excruciatingly difficult in VBScript. The
' method used here forks "cmd /c pause" with .Exec, and then uses the returned .Exec object's .ProcessID
' attribute to feed into WMI to get that process's Win32_Process descriptor object, and then uses THAT
' WMI Win32_Process descriptor object's .ParentProcessId attribute, which will be OUR Process ID, and finally
' we terminate the waiting cmd process. Execing cmd is what causes the brief cmd window to flash at start up,
' and I can' figure out out how to hide that window.
' returns: My own Process ID as a long int; zero if we can't get it.
' ************************************************************************************************************
Function lng_MyProcessID ()
lng_MyProcessID = 0 ' Initially assume failure
If objWMIService Is Nothing Then Exit Function ' Should only happen if in Guest or other super-limited account
Set objChildProcess = objWshShell.Exec ( """%ComSpec%"" /C pause" ) ' Fork a child process that just waits until its killed
Set colPIDs= objWMIService.ExecQuery ( "Select * From Win32_Process Where ProcessId=" & objChildProcess.ProcessID,, 0 )
For Each objPID In colPIDs ' There's exactly 1 item, but .ItemIndex(0) doesn't work in XP
lng_MyProcessID = objPID.ParentProcessId ' Return child's parent Process ID, which is MY process ID!
Next
Call objChildProcess.Terminate() ' Terminate our temp child
End Function ' lng_MyProcessID
I like Kul-Tigin's idea (+1), and Asok Smith's idea (based on .Exec) deserve respect (+1), and it w'd been even better if .Exec run hidden process. So, to feed my curiosity, I also toyed with this and this's what I did.
ts1 = Timer : res1 = CurrProcessId : te1 = Timer - ts1
ts2 = Timer : res2 = ThisProcessId : te2 = Timer - ts2
WScript.Echo "CurrProcessId", res1, FormatNumber(te1, 6), _
vbCrLf & "ThisProcessId", res2, FormatNumber(te2, 6), _
vbCrLf & "CurrProcessId / ThisProcessId = " & te1 / te2
'> CurrProcessId 6946 0,437500
'> ThisProcessId 6946 0,015625
'> CurrProcessId / ThisProcessId = 28
Function ThisProcessId
ThisProcessId = 0
Dim sTFile, oPrc
With CreateObject("Scripting.FileSystemObject")
sTFile = .BuildPath(.GetSpecialFolder(2), "sleep.vbs")
With .OpenTextFile(sTFile, 2, True)
.Write "WScript.Sleep 1000"
End With
End With
With CreateObject("WScript.Shell").Exec("WScript " & sTFile)
For Each oPrc In GetObject("winmgmts:\\.\root\cimv2").ExecQuery(_
"Select * From Win32_Process Where ProcessId=" & .ProcessID)
Exit For : Next
ThisProcessId = oPrc.ParentProcessId
End With
End Function
28 times faster(!), not bad :)
You may use Sleep from kernel32 instead of mshta.
MsgBox GetProcId()
Function GetProcId()
With GetObject("winmgmts:\\.\root\CIMV2:Win32_Process.Handle='" & CreateObject("WScript.Shell").Exec("rundll32 kernel32,Sleep").ProcessId & "'")
GetProcId = .ParentProcessId
.Terminate
End With
End Function
Code taken from here.
Also there is parent process name detection based on this approach.
Here is a better one, but in JScript (sorry, you translate it to VB ...)
var WshShell = WScript.CreateObject("WScript.Shell");
var objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\\\.\\root\\cimv2");
var childProcess =
WshShell.Exec
(
'"' + WshShell.Environment('PROCESS')('ComSpec') + '"'
+
" /C Echo \"Text lines\" && Set /p VarName="
);
childProcess.StdOut.ReadLine();
var current_pid =
objWMIService.ExecQuery
(
"Select * From Win32_Process Where ProcessId=" + childProcess.ProcessID
);
current_pid = (new Enumerator(current_pid)).item().ParentProcessId;
if (current_pid)
{
childProcess.StdIn.WriteLine("value"); // child process should now exit
WScript.Echo("Current PID: " + current_pid);
}
else
{
WScript.StdErr.WriteLine("Get current PID from WMI failed.");
WScript.Quit(7);
}
I just found this thread that partly solved my problem.
Thank you all.
"the code is unable to determine which process ID belongs to which script" : true, but as this is the first task that your script must achieve , you can keep the Pid that has the shortest lifetime.
Set com = CreateObject("Wscript.Shell")
Set objSWbemServices = GetObject ("WinMgmts:Root\Cimv2")
Set colProcess = objSWbemServices.ExecQuery ("Select * From Win32_Process")
dim toto, thisPid
thisPid=""
toto=200 ' just a high value like 200sec
For Each objProcess In colProcess
If InStr (objProcess.CommandLine, WScript.ScriptName) <> 0 Then
Ptime=((Cdbl(objProcess.UserModeTime)+Cdbl(objProcess.KernelModeTime))/10000000)
if toto > Ptime then
toto = Ptime
thisPid = objProcess.ProcessId
End If
End If
Next
If thisPid="" then
WScript.Echo "unable to get the PID"
Else
WScript.Echo "PID of this script : "&thisPid
End If
Except if you fired scripts quicker more than each one can retrieve their Pid, everything must be ok.
To retrieve the own process ID of a VB Script you can rely on the property CreationDate of the Process object.
At the moment a VB Script is started, the process that runs the script will have the latest CreationDate of all processes that runs the same script.
In fact, it will have the highest CreationDate of all running processes.
So, to get the PID, first thing to do is to search for the process with the highest CreationDate.
'Searching for processes
Dim strScriptName
Dim WMI, wql
Dim objProcess
'
'My process
Dim datHighest
Dim lngMyProcessId
'Which script to look for ?
strScriptName = "WScript.exe"
'strScriptName = "Notepad.exe"
'Iniitialise
datHighest = Cdbl(0)
Set WMI = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
wql = "SELECT * FROM Win32_Process WHERE Name = '" & strScriptName & "'"
'
For Each objProcess In WMI.ExecQuery(wql)
'The next If is not necessary, it only restricts the search to all processes on the current VB Script
'If Instr(objProcess.CommandLine, WScript.ScriptName) <> 0 Then
If objProcess.CreationDate > datHighest Then
'Take the process with the highest CreationDate so far
' e.g. 20160406121130.510941+120 i.e. 2016-04-06 12h11m:30s and fraction
datHighest = objProcess.CreationDate
lngMyProcessId = objProcess.ProcessId
End If
'End If
Next
'Show The result
WScript.Echo "My process Id = " & lngMyProcessId
Powershell can be used to retrieve the calling VBScript process ID. This approach utilizes the optional argument of the exit command which specifies the program's exit code. And, if the optional 3rd argument of the WShell.Run method is set to True, then it will return the exit code (which is the VBScript process ID) after powershell has closed.
Dim sCmd
Dim WShell
sCmd = _
"powershell -command exit " & _
"(gwmi Win32_Process -Filter " & _
"\""processid='$PID'\"").parentprocessid"
Set WShell = CreateObject("WScript.Shell")
MsgBox WShell.Run(sCmd, 0, True)
This is not my answer, I found this in some google groups discussion forum... See if it helps you.
Set objSWbemServices = GetObject ("WinMgmts:Root\Cimv2")
Set colProcess = objSWbemServices.ExecQuery ("Select * From Win32_Process")
For Each objProcess In colProcess
If InStr (objProcess.CommandLine, WScript.ScriptName) <> 0 Then
WScript.Echo objProcess.Name, objProcess.ProcessId, objProcess.CommandLine
End If
Next
Original Discussion Thread in Google Groups forum
Get the current processID
Set WshShell = CreateObject("WScript.Shell")
currentProgram=wscript.ScriptName
Const strComputer = "."
Dim objWMIService, colProcessList
Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
query="SELECT * FROM Win32_Process WHERE Name = 'wscript.exe' "
Set colProcessList = objWMIService.ExecQuery(query)
For Each objProcess in colProcessList
If (InStr (objProcess.commandLine,wscript.ScriptName) <> 0 )Then
processDetails="Current ProcessId : "& objProcess.ProcessId & " \n, And Process Name:" & objProcess.name &"\n CommandLine is :"& objProcess.CommandLine
message = msgbox(processDetails,16,"Details")
End If
I used this to get a scripts own process id.
Function GetPid()
GetPid=GetObject("winmgmts:\\.\root\CIMV2").ExecQuery("Select * From Win32_Process Where CommandLine Like '%" &Wscript.ScriptName& "%'").ItemIndex(0).ProcessId
End Function
Wscript.Echo GetPid()
This is a VBScript code example that shows how to catch whatever a command line program sends to standard output.
It executes the command xcopy /? and shows the output in a message box. Before the message box appears, for a split second you see the console window popping up.
Set objShell = WScript.CreateObject("WScript.Shell")
Set objExec = objShell.Exec("xcopy /?")
Do
line = objExec.StdOut.ReadLine()
s = s & line & vbcrlf
Loop While Not objExec.Stdout.atEndOfStream
WScript.Echo s
Here is an other VBScript code example that shows how to execute a script without showing the console window.
objShell.Run "c:\temp\mybatch.bat C:\WINDOWS\system32\cmd.exe", 0
or
objShell.Run "c:\temp\myscript.vbs C:\WINDOWS\system32\cscript.exe", 0
As you can see it has the form <script><space><executor>.
The last example uses objShell.Run instead of objShell.Exec
What I don't know is how to execute a command line program (if necessary from a batch file), catch the standard output, without showing the console window. Any ideas?
I usually use this:
Wscript.echo execStdOut("ping google.com")
Function execStdOut(cmd)
Dim goWSH : Set goWSH = CreateObject( "WScript.Shell" )
Dim aRet: Set aRet = goWSH.exec(cmd)
execStdOut = aRet.StdOut.ReadAll()
End Function
For more advanced commands youc an wrap to comspec (cmd)
my res = execStdOut("%comspec%" & " /c " & """" & "dir /b c:\windows\*.exe" & """" & " && Echo. && Echo finished")
In order to redirect the output to the console, run the script using cscript, ex.: c:\cscript myscript.vbs.
cscript has a few command line options. The most important (to me) is the switch //NOLOGO. If yoy use it (cscript //nologo myscript.vbs) it will omit Microsoft merchandise...
This proof of concept script:
' pocBTicks.vbs - poor man's version of backticks (POC)
Option Explicit
' Globals
Const SW_SHOWMINNOACTIVE = 7
Const ForReading = 1
Dim goFS : Set goFS = CreateObject( "Scripting.FileSystemObject" )
Dim goWSH : Set goWSH = CreateObject( "WScript.Shell" )
' Dispatch
WScript.Quit demoBTicks()
' demoBTicks -
Function demoBTicks()
demoBTicks = 1
Dim aCmds : aCmds = Array( _
"dir pocBTicks.vbs" _
, "dur pocBTicks.vbs" _
, "xcopy /?" _
)
Dim sCmd
For Each sCmd In aCmds
WScript.Echo "########", sCmd
Dim aRet : aRet = BTicks( sCmd )
Dim nIdx
For nIdx = 0 To UBound( aRet )
WScript.Echo "--------", nIdx
WScript.Echo aRet( nIdx )
Next
Next
demoBTicks = 0
End Function ' demoBTicks
' BTicks - execute sCmd via WSH.Run
' aRet( 0 ) : goWSH.Run() result
' aRet( 1 ) : StdErr / error message
' aRet( 2 ) : StdOut
' aRet( 3 ) : command to run
Function BTicks( sCmd )
Dim aRet : aRet = Array( -1, "", "", "" )
Dim sFSpec2 : sFSpec2 = goFS.GetAbsolutePathName( "." )
Dim sFSpec1 : sFSpec1 = goFS.BuildPath( sFSpec2, goFS.GetTempName() )
sFSpec2 = goFS.BuildPath( sFSpec2, goFS.GetTempName() )
aRet( 3 ) = """%COMSPEC%"" /c """ + sCmd + " 1>""" + sFSpec1 + """ 2>""" + sFSpec2 + """"""
Dim aErr
On Error Resume Next
aRet( 0 ) = goWSH.Run( aRet( 3 ), SW_SHOWMINNOACTIVE, True )
aErr = Array( Err.Number, Err.Description, Err.Source )
On Error GoTo 0
If 0 <> aErr( 0 ) Then
aRet( 0 ) = aErr( 0 )
aRet( 1 ) = Join( Array( aErr( 1 ), aErr( 2 ), "(BTicks)" ), vbCrLf )
BTicks = aRet
Exit Function
End If
Dim nIdx : nIdx = 1
Dim sFSpec
For Each sFSpec In Array( sFSpec2, sFSpec1 )
If goFS.FileExists( sFSpec ) Then
Dim oFile : Set oFile = goFS.GetFile( sFSpec )
If 0 < oFile.Size Then
aRet( nIdx ) = oFile.OpenAsTextStream( ForReading ).ReadAll()
goFS.DeleteFile sFSpec
End If
End If
nIdx = nIdx + 1
Next
BTicks = aRet
End Function
shows how to use .Run and temporary files to get something like backticks with a hidden console. Decent file handling, quoting in sCmd, cleaning of the returned strings, and dealing with encodings will require more work. But perhaps you can use the strategy to implement something that fits your needs.
If you don't mind having the taskbar button appear, you can just move the console window offscreen before launching it.
If the HKCU\Console\WindowPosition key exists, Windows will use its value to position the console window. If the key doesn't exist, you'll get a system-positioned window.
So, save the original value of this key, set your own value to position it offscreen, call Exec() and capture its output, then restore the key's original value.
The WindowPosition key expects a 32-bit value. The high word is the X coordinate and the low word is the Y coordinate (XXXXYYYY).
With CreateObject("WScript.Shell")
' Save the original window position. If system-positioned, this key will not exist.
On Error Resume Next
intWindowPos = .RegRead("HKCU\Console\WindowPosition")
On Error GoTo 0
' Set Y coordinate to something crazy...
.RegWrite "HKCU\Console\WindowPosition", &H1000, "REG_DWORD"
' Run Exec() and capture output (already demonstrated by others)...
.Exec(...)
' Restore window position, if previously set. Otherwise, remove key...
If Len(intWindowPos) > 0 Then
.RegWrite "HKCU\Console\WindowPosition", intWindowPos, "REG_DWORD"
Else
.RegDelete "HKCU\Console\WindowPosition"
End If
End With
If you really want to make sure the coordinates are offscreen, you can get the screen dimensions via VBScript by using IE or other tools.
To return in VBA all subfolders in G:\OF
sub M_snb()
c00= createobejct("wscript.Shell").exec("cmd /c Dir G:\OF\*. /s/b").stdout.readall
end sub
to split the returned string into an array
sub M_snb()
sn=split(createobejct("wscript.Shell").exec("cmd /c Dir G:\OF\*. /s/b").stdout.readall,vbCrLf)
for j=0 to ubound(sn)
msgbox sn(j)
next
End Sub
This is the way you can get the command line StdOut (result) without see this popup black dos windows in vbscript:
Set Sh = CreateObject("WScript.Shell")
tFile=Sh.ExpandEnvironmentStrings("%Temp%")&"\t.txt"
Sh.Run "cmd.exe /c xcopy /? > """&tFile&""" ",0,False
Wscript.echo CreateObject("Scripting.FileSystemObject").openTextFile(tFile).readAll()
Instead of WScript.Shell, consider using using Win32_Process with startupInfo.ShowWindow = 0 to launch the process with SW_HIDE. I posted a detailed example under VBS Run cmd.exe output to a variable; not text file.
To monitor the bandwidth usage and not to unnecessarily load programs in the start up,I want to execute the dumeter.exe then firefox.exe.When I shutdown firefox it should kill dumeter.I used the following code to start
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run "c:\progra~1\dumeter\dumeter.exe"
WshShell.Run "c:\progra~1\mozill~1\firefox.exe
Need to run taskkill only when firefox is closed.Tried using a bat file but sometimes the dumeter starts and closes on its own does not wait.
WshShell.Run "taskkill /f /im dumeter.exe"
Set WshShell = Nothing
You can wait for a process to end by subscribing to the appropriate WMI event. Here's an example:
strComputer = "."
Set oWMI = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
''# Create an event query to be notified within 5 seconds when Firefox is closed
Set colEvents = oWMI.ExecNotificationQuery _
("SELECT * FROM __InstanceDeletionEvent WITHIN 5 " _
& "WHERE TargetInstance ISA 'Win32_Process' " _
& "AND TargetInstance.Name = 'firefox.exe'")
''# Wait until Firefox is closed
Set oEvent = colEvents.NextEvent
More info here: How Can I Start a Process and Then Wait For the Process to End Before Terminating the Script?
Option Explicit
Const PROC_NAME = "<Process_You_Want_to_Check>"
Const SLEEP_INTERVAL_MS = 5000 '5 secs
Dim objWMIService
Dim colProcesses, objProcess, inteproc
Set objWMIService = GetObject("winmgmts:\\.\root\cimv2")
inteproc = -1 'set in unknown state
Do Until inteproc = 0
Set colProcesses = objWMIService.ExecQuery(_
"Select * from Win32_Process where Name='" & PROC_NAME & "'")
inteproc = colProcesses.count
If inteproc > 0 then
WSCRIPT.ECHO "Process " & PROC_NAME & " is still runing, wait for " & SLEEP_INTERVAL_MS / 1000 & " seconds"
WScript.Sleep(SLEEP_INTERVAL_MS)
else
wscript.echo "Process " & PROC_NAME & " Finished. Continue running scripts"
End If
Loop