I'm trying to make a vb script that will restart another vb script if it crashes.
I have searched, and searched but all I get is how to restart a program and since a vb script is a background process it doesn't work when you search in Win32_Process.
Here is my code
set Service = GetObject ("winmgmts:")
set Shell = WScript.CreateObject("WScript.Shell")
sEXEName = "Test_To_Block.vbs"
while true
bRunning = false
for each Process in Service.InstancesOf ("Win32_Process")
if Process.Name = sEXEName then
bRunning=true
msgbox("I am active")
End If
next
if bRunning=False then
msgbox("I am not active.")
Shell.Run sEXEName
end if
WScript.Sleep(100)
wend
The problem is that it never see's the file running and just opens hundreds of "Test_To_Stop.vbs"'s which resolves in me having to restart the computer.
In my opinion what should be changed is where the code is looking for.
for each Process in Service.InstancesOf ("Win32_Process")
Instead of looking in "Win32_Process" you need to look in wherever background process' run.
I am new to coding so sorry if this is a simple question.
Thank you in advance.
Regards,
A Viper
The below code restarts itself via WshShell.Exec() method and trace state of the running script via .Status property of returned object:
If Not WScript.Arguments.Named.Exists("task") Then
Do
With CreateObject("WScript.Shell").Exec("""" & WScript.FullName & """ """ & WScript.ScriptFullName & """ ""/task""")
Do While .Status = 0
WScript.Sleep 1
Loop
End With
Loop
End If
MsgBox "This script will be restarted immediately after termination"
Another way is to use .Run() method with third parameter set to True to wait until launched process terminated:
If Not WScript.Arguments.Named.Exists("task") Then
Do
CreateObject("WScript.Shell").Run """" & WScript.FullName & """ """ & WScript.ScriptFullName & """ ""/task""", 1, True
Loop
End If
MsgBox "This script will be restarted immediately after termination"
Or even simplier:
If Not WScript.Arguments.Named.Exists("task") Then
Do
CreateObject("WScript.Shell").Run """" & WScript.ScriptFullName & """ ""/task""", 1, True
Loop
End If
MsgBox "This script will be restarted immediately after termination"
Probably because the name of the running process is 'wscript.exe' and not 'Test_To_Block.vbs'. You may be able to use the hack mentioned on this page to change the name of the process:
If you're running the scripts locally and running some regular scripts, one
common hack is just to copy and rename wscript.exe to a particular name,
such as "MyScript1.exe". Then run the script with a shortcut as
"...\MyScript1.exe MyScript1.vbs". Then the process will show up as
MyScript1.exe.
Then you can use sEXEName = "MyScript1.exe"
Note: instead of using Shell.run sExeName use Shell.run "Test_To_Block.vbs"
Related
I am running the following VBScript (check.vbs):
Set service = GetObject ("winmgmts:")
For Each Process In Service.InstancesOf("Win32_Process")
If Process.Name = "cmd.exe" Then
WScript.Echo "cmd running"
WScript.Quit
End If
Next
CreateObject("WScript.Shell").Run("C:\system\file.bat")
This script will check whether cmd.exe is running or not. If it is running, this script will display a message "cmd running". If it is not running, this script will open a batch file C:\system\file.bat.
But what I actually need is: when I run this script check.vbs it needs to keep on checking until it finds that cmd.exe is not running.
Only if it found cmd.exe is not running it needs to run file.bat - after repeated checking in background (like any loop program).
In simple words, when opening check.vbs the script need to continously check that cmd.exe is running or not, once it found it's not running, it need to open file.bat.
Still not sure if I understand the question correctly, but assuming that you actually want a monitor that watches and re-spawns a particular process you could do something like this:
Set wmi = GetObject ("winmgmts://./root/civm2")
Sub CheckProcess(name, script)
For Each p In wmi.ExecQuery("SELECT * FROM Win32_Process")
If p.Name = name Then Exit Sub
Next
CreateObject("WScript.Shell").Run script
End Sub
Do
CheckProcess "cmd.exe", "C:\system\file.bat"
WScript.Sleep 100
Loop
I feel like this should be easy, but I haven't figured it out yet.
I have an executable that is already running when I run my vbscript. I want to find the executable and call sendkeys to give it input.
Here is what I have so far:
dim service, Process, myObject
set service = GetObject ("winmgmts:")
for each Process in Service.InstancesOf ("Win32_Process")
if Process.Name = "abc.exe" then
myObject = Process
end if
next
myObject.SendKeys "This is a test."
This doesn't work, but I think it would look similar to this. I basically just want to sendkeys to myObject.
NOTE: I do not want to run a new instance of abc.exe, I want to send input to the one that is already running
You are trying to activate a wscript submethod(sendkeys) off of a process, this does not have a sendkeys submethod. Try the "App Activate" submethod off of the wscript shell....
Set objShell = WScript.CreateObject("WScript.Shell")
Do Until Success = True
Success = objShell.AppActivate("ABC")
Wscript.Sleep 1000
Loop
objShell.SendKeys "This is a test."
Reference
We currently use Windows Batch (DOS) command files to control our process flow. To display messages to the Console, we would use the ECHO command. These messages would show up in our Scheduler software, which used to be Tivoli and now is CA WA Workstation\ ESP.
I would like to start using VBS files instead of CMD\BAT files and am trying to figure out how to do the equivalent of an ECHO to the console.
When I try to use either the WScript.Echo command or write to Standard Out, the messages are displayed in dialog boxes for both and they require the OK button to be pushed to continue. Not surprisingly, when I run unattended though a scheduler, the job hits one of these commands and just hangs since there is no one to OK the messagebox.
SET FS = CreateObject("Scripting.FileSystemObject")
SET StdOut = FS.GetStandardStream(1)
StdOut.Write("Test 1")
WScript.echo("Test 2")
I realize I could write the messages to a Log file using the Scripting object, but this could fail if an invalid path is provided or because of insufficient permissions. Besides, being able to see feedback write within the Scheduler is awfully convenient.
How do I write to the Console using VBScript? I’ve seen other posts here that suggest that the above methods which didn't work for the reason describe above were the way to do it.
wscript.echo is the correct command - but to output to console rather than dialogue you need to run the script with cscript instead of wscript.
You can resolve this by
running your script from command line like so:
cscript myscript.vbs
changing the default file association (or creating a new file extension and association for those scripts you want to run with cscript).
change the engine via the script host option (i.e. as per http://support.microsoft.com/kb/245254)
cscript //h:cscript //s
Or you can add a few lines to the start of your script to force it to switch "engine" from wscript to cscript - see http://www.robvanderwoude.com/vbstech_engine_force.php (copied below):
RunMeAsCScript
'do whatever you want; anything after the above line you can gaurentee you'll be in cscript
Sub RunMeAsCScript()
Dim strArgs, strCmd, strEngine, i, objDebug, wshShell
Set wshShell = CreateObject( "WScript.Shell" )
strEngine = UCase( Right( WScript.FullName, 12 ) )
If strEngine <> "\CSCRIPT.EXE" Then
' Recreate the list of command line arguments
strArgs = ""
If WScript.Arguments.Count > 0 Then
For i = 0 To WScript.Arguments.Count
strArgs = strArgs & " " & QuoteIt(WScript.Arguments(i))
Next
End If
' Create the complete command line to rerun this script in CSCRIPT
strCmd = "CSCRIPT.EXE //NoLogo """ & WScript.ScriptFullName & """" & strArgs
' Rerun the script in CSCRIPT
Set objDebug = wshShell.Exec( strCmd )
' Wait until the script exits
Do While objDebug.Status = 0
WScript.Sleep 100
Loop
' Exit with CSCRIPT's return code
WScript.Quit objDebug.ExitCode
End If
End Sub
'per Tomasz Gandor's comment, this will ensure parameters in quotes are covered:
function QuoteIt(strTemp)
if instr(strTemp," ") then
strTemp = """" & replace(strTemp,"""","""""") & """"
end if
QuoteIt = strTemp
end function
currently, to improve some inefficiencies on a daily process, I am trying to write a c# Winform app that will combine a mix of user-input with VBscripts that will expedite a previously all user-input process of looking at an excel file and moving files from VSS to certain folders of certain servers.
I was hoping to get some questions answered, pointed in the right way:
Using command line or other workaround instead of manually,
1) Is it possible to log into a 2003 remote desktop with a Smartcard/pin?
2) Is it possible to run a file/start a process on the remote desktop from a command on your machine?
Thanks for the help and time
I have only experience with the second question.
You can do this with remote scripting or with utilities like SysInternals PsExec http://technet.microsoft.com/en-us/sysinternals/bb897553.aspx
here a vbscript that remotely starts a ipconfig command and redirects it to a textfile
Note that you can't start interactive processes like this, they would start but not show up
Dim sComputer 'computer name
Dim sCmdLine 'command line of the process
Dim sCurDir 'working directory of the process
Dim oProcess 'object representing the Win32_Process class
Dim oMethod 'object representing the Create method
sComputer = "." 'this is the local computer, use a pcname or ip-adress to do it remote
sCmdLine = "cmd /c ipconfig.exe > c:\ipconfig.txt"
Set oProcess = GetObject("winmgmts://" & sComputer & "/root/cimv2:Win32_Process")
Set oMethod = oProcess.Methods_("Create")
Set oInPar = oMethod.inParameters.SpawnInstance_()
oInPar.CommandLine = sCmdLine
oInPar.CurrentDirectory = sCurDir
Set oOutPar = oProcess.ExecMethod_("Create", oInPar)
If oOutPar.ReturnValue = 0 Then
WScript.Echo "Create process method completed successfully"
WScript.Echo "New Process ID is " & oOutPar.ProcessId
Else
WScript.Echo "Create process method failed"
End If
I like to end a process using VBScript.
Unfortunally I only found examples in which the authors are describing how to do it killing the process.
I like to ask for closing. So objProcess.Terminate() won't help.
I'm using Windows XP SP3 with admin rights.
Any Ideas?
Thank you!
You could try the CloseMainWindow and the Close methods on the process as described on MSDN, like:
Sub KillingMeSoftly(processName)
'partly copied from http://www.activexperts.com/activmonitor/windowsmanagement/adminscripts/processes/
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colProcessList = objWMIService.ExecQuery _
("Select * from Win32_Process Where Name = '" & processName & "'")
For Each objProcess in colProcessList
objProcess.CloseMainWindow
objProcess.Close
Next
End Sub
this was a bad answer
UPDATE
While searching for an answer, I just discovered that starting a script with the //T:nn option triggers the Terminate event on objects:
class Foo
sub class_terminate
msgbox "Gracefull termination"
' Put your own termination code here.
end sub
end class
dim bar
set bar = new Foo
do
loop ' makes the script run forever
Save this as c:\endless.vbs
Running this script will never trigger the termination event because it will hang in the endless loop, but if you start the script with a timeout it will; Start the script from the command prompt:
C:\>wscript endless.vbs //T:5
You'll see that after 5 seconds a messagebox with "Gracefull termination" appears.
This is usefull when you want to quit a script after a certain amount of time and run a cleanup if it was not ended by itself. I do not know if this covers the solution you are searching for.
So, finally I found a solution for my problem, but is not solved using VBS.
There is a program written to send a CTRL-BREAK to any process called "SendSignal". I had tried this before, but all my process was responding had been an error-message and it kept running.
I changed this program sending CTRL+C. After this I was able to shut my Javaw process gently.
Thanks to all, for your help!