Activate a running process with known process ID using VBScript - vbscript

I have the process ID of the process for my application that is already running.
Now I want to activate that same window through this process id with VBScript.
Supposing mypid is the process ID
Set Shell = CreateObject("WScript.Shell")
Shell.AppActivate(mypid)
This is returning false on Windows 7.
If anyone has an answer, I would like to know it.

Check this link :
WshShell.AppActivate doesn't seem to work in simple vbs script
And this is the summary of good solution there:
Set WshShell = CreateObject("WScript.Shell")
for i=0 to 300 'this loop will continue about 30 sec if this not enough increase this number
Rtn=WshShell.AppActivate(myPID) 'have to be the windows title of application or its process ID
If Rtn = True Then
WshShell.SendKeys "......." ' send key you like
wscript.sleep 100 ' stop execute next line until finish close app
End If
wscript.sleep 100
Next

Related

Scheduling a task to be performed at logon (of any user) in vbScript

Alright so I have been searching for the answer to this, and although I found similar examples to this issue, they did not seem to work for me. I am trying to have a task scheduled to kill skype when a user logs in so that people don't have to close out every time they log on. I have to do this by writing code rather than manually because it will be a script run to set up new computers. here is my code that writes the task:
please note that the commented lines are from solutions I have tried but failed to work the way I wanted it to
Option Explicit
Dim wShell, outFile, objFSO, ret
Set wShell = CreateObject ("Wscript.Shell")
wShell.Run "N:\Internfolder\INCA_Scripts\SkypeKill.vbs"
'wShell.Run "cmd start ""N:\Internfolder\INCA_Scripts\Schedule_SkypeKill.bat"""
'wShell.Run "N:\Internfolder\INCA_Scripts\Schedule_SkypeKill.bat"
wShell.Run "SCHTASKS /create /tn ""Schedule_Kill_Skype"" /tr ""N:\Internfolder\INCA_Scripts\SkypeKill.vbs"" /sc onlogon", 0
'set wShell = Nothing
'WScript.sleep(15000)
WScript.echo "completed"
and here is the .vbs file for SkypeKill:
Dim oShell : Set oShell = CreateObject("WScript.Shell")
dim timer
timer = 0
Do
'attempt to kill skype (lync.exe)
r = oShell.Run("taskkill /F /IM lync.exe",0, True)
'if r = 0, then skyp was opened, then killed
if r= 0 then
WScript.echo "Skype was opened, but has been termiated. Hit 'Enter' to exit."
WScript.quit
'else, we wait until it is opened for 35 seconds, and kill it if it appears
else
WScript.sleep(3000)
timer = timer + 3
if timer = 35 Then Exit Do
end if
Loop
WScript.echo "Skype kill has been attempted"
the last bit of important information is that when I schedule the task to run this script, it says that the system cannot find the file specified, however the SkypeKill.vbs file is in the specified location (N:\Internfolder\INCA_Scripts\SkypeKill.vbs), which is a bit odd.
So with this I have a couple questions. I am assuming that there is something wrong with how I am attempting to schedule the task, given that it will not show up in the task scheduler when i run the first block of code. but, neither code throws any errors. How can I get this to actually write into the task scheduler and kill skype once the user has logged in and started up? Does the fact that I am running on Windows 7 and Windows 10 matter when trying to complete this task? or is there an easier way to do this via code that I am overlooking. Please help soon! Thanks!
Thank you, However I have resolved the issue simply by including the following code before the shell functions are executed:
If WScript.Arguments.Count = 0 Then
Set objShell = CreateObject("Shell.Application")
objShell.ShellExecute "wscript.exe", "c:\Users\admin\Documents\selfConfigure.vbs -1", "", runas", 1
End If
this elevates my priveleges to access the drive/file paths I need to access, as I was receiving an "access denied" error in command prompt. the issue has been resolved and the task has been written to the scheduler.

How to run loop check vbs for particular running process? Or missing process?

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

Restart a vbs script if it crashes

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"

Open VBS from hyperlink

I created a hyperlink in a pdf, this hyperlink is tied to vbs script, until this step all ok. When I run the script manually (double click), the script does that I want (open telnet connection). The problem is when I run the script through the hyperlink, CMD show the message " "telnet" is not recognized as an internal or external command". Please, Can anyone tell me why occurs that??
This is the script:
Dim WshShell, regexp
set regular = New RegExp
direccion = inputbox("Ingresa ip del equipo:")
' Set pattern.
regular.Pattern = "^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$"
' Set case insensitivity.
regular.IgnoreCase = True
' Set global applicability.
regular.Global = True
if regular.test(direccion) = TRUE then
set WshShell=CreateObject("WScript.Shell")
WshShell.run "cmd.exe"
WScript.Sleep 1000
'Send commands to the window as needed - IP and commands need to be customized
'Step 1 - Telnet to remote IP'
WshShell.SendKeys "telnet " & direccion
WshShell.SendKeys ("{Enter}")
WScript.Sleep 1000
else
msgbox "Ingresa una ip vĂ¡lida"
end if
probably working directory not set correctly.
try
WshShell.SendKeys "c:\windows\system32\telnet.exe " & direccion
p.s: you're doing it wrong. "sendkeys" is somehow understandable when telnet terminal is already running, but there is no reason to be manually sending keys to the standard command prompt.
Telnet isn't in my Windows 10 and 8. But anyway if you have "telnet" command couldn't you do:
WshShell.run "cmd.exe /k telnet"
That should work and saves space.

Vbscript. How do you sendkeys to a SWbemObject?

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

Resources