vbscript start .exe without command prompt with priority [duplicate] - cmd

This question already has an answer here:
Prevent VBscript app from showing Console Window
(1 answer)
Closed 1 year ago.
Hey guys im trying to start a programm hidden with less priority but the command prompt still pop out.
Dim WShell
Set WShell = CreateObject("WScript.Shell")
WShell.Run "cmd /c Start /belowNormal " & "C:\Users\Desktop\sonso.exe -uri www.google.de",0
Set WShell = Nothing

You asked how to reduce exe priority from VBS without using CMD so here is an example.
(I admit it is not all my own work, but performs as advertised for Notepad.exe)
Don't ask me exactly how it works and it took me ages to find as the vbs example is "missing" from the Microsoft setpriority-method-in-class-win32-process link I include.
Set Priority.vbs
' Set priority of process to Below Normal on Server 2008 & Vista+'
' From https://learn.microsoft.com/en-gb/windows/win32/cimwin32prov/setpriority-method-in-class-win32-process'
' Below Normal (16384) Indicates a process that has priority above IDLE_PRIORITY_CLASS (64),'
' but below NORMAL_PRIORITY_CLASS (32). NOTE:- combined namespace is \\. \Root\CIMV2
' Others ABOVE_NORMAL (32768) HIGH_PRIORITY (128) *REAL_TIME ( 256) *Note To set Realtime,
' the caller must have SeIncreaseBasePriorityPrivilege (SE_INC_BASE_PRIORITY_PRIVILEGE).
' Without this privilege, the highest the priority can be set to is High Priority.
' Use your RUN commands here and replace name = Notepad.exe below or replace Notepad.exe with arg[0]
Set objShell = WScript.CreateObject("WScript.Shell")
' With CMD but minimised so we can open it from taskbar
' objShell.Run "%comspec% /d /c start /min Notepad.exe fred.txt", 0, True
' Without CMD BUT NOT hidden, otherwise how are you going to edit anything or close Notepad.
objShell.Run "c:\windows\Notepad.exe fred.txt"
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\Root\CIMV2")
Set colProcesses = objWMIService.ExecQuery _
("Select * from Win32_Process Where Name = 'Notepad.exe'")
For Each objProcess in colProcesses
objProcess.SetPriority(16384)
Next

Related

Trying to press keys and shortcuts in a hidden CMD window

I am trying to create a script that will use the copy con to write a file
Set objNetwork = CreateObject("Wscript.Network")
CurrentUser = objNetwork.UserName
Set Wshell = CreateObject("WScript.Shell")
Wshell.Run "%COMSPEC% cd C:\Users\" & CurrentUser & _
"\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup & copy con master.vbs & x = 1 & x=2^Z", 0, True
The problem here is that while using ^Z does simulate the output of Crtl+Z, CMD doesn't treat them the same.
As you can see, I wanted the console window to be hidden, so using something like SendKeys won't work here.
Any suggestions?

How to get running application name by vbscript

I would like to get the name list of running application by vbscript and kill the application by its main window title. Those applications should be listed on Task Manager -> Applications tab
Like this:
After searching from web, I found vbscript like this:
'FUNCTION
Function ListProcessRunning()
'This function can report names from
'TaskManager -> Processes
sComputerName = "."
Set objWMIService = GetObject("winmgmts:\\" & sComputerName & "\root\cimv2")
sQuery = "SELECT * FROM Win32_Process"
Set objItems = objWMIService.ExecQuery(sQuery)
'iterate all item(s)
For Each objItem In objItems
WScript.Echo objItem.Name
Next
End Function
This vbscript list all process names which are under Task Manager -> Processes tag like this:
Which is not what I want.
I also found this:
'FUNCTION
Function ListApplicationRunning()
'This function can report names from
'TaskManager -> Application
Set Word = CreateObject("word.application")
For Each x In Word.Tasks
WScript.Echo x.Name
Next
Word.Quit
Set Word = Nothing
End Function
Which really give me what I want but the problem is the server I am going to run this script has no Word so no word.application for vbscript and I am not able to install one for it.
My question is how to get the application name and kill the application by that name? I am not sure is it possible to do with vbscript only, may be a combination of vbscript and cmd is also okay.
In vbscript we can do something like that just give a try with it :
Option Explicit
Call KillProcessbyName("common-api.jar")
'*********************************************************************************
Sub KillProcessbyName(FileName)
On Error Resume Next
Dim WshShell,strComputer,objWMIService,colProcesses,objProcess
Set WshShell = CreateObject("Wscript.Shell")
strComputer = "."
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colProcesses = objWMIService.ExecQuery("SELECT * FROM Win32_Process")
For Each objProcess in colProcesses
If InStr(objProcess.CommandLine,FileName) > 0 Then
If Err <> 0 Then
MsgBox Err.Description,VbCritical,Err.Description
Else
objProcess.Terminate(0)
End if
End If
Next
End Sub
'**********************************************************************************
FOR /F "usebackq tokens=1-2" %i IN (`tasklist ^|findstr /b "notepad"`) DO taskkill /PID %j

Use VBS to run PowerShell

So I have a .ps1 file which creates a form.
That Form takes 10-20secs depending on PCs performance and connection on first load.
Now I am currently using VBS to load a simple .gif file as a loading screen concurrently running the .ps1 file right after.
My issue at the moment is that, I want to close the loading screen when the form pops up. I tried to determine via processes but that failed because of the it loads powershell.exe but the form takes 10sec...
Is it this possible?
Of have you guys got a better idea to do this?
Dim i
Dim strComputer
Dim FindProc
Dim counter
counter = 0
strComputer = "."
FindProc = "powershell.exe"
'Load the gif file
Set objExplorer = CreateObject("InternetExplorer.Application")
With objExplorer
.Navigate "about:blank"
.Visible = 1
.Document.Title = "Show Image"
.Toolbar=False
.Statusbar=False
.Top=400
.Left=400
.Height=355
.Width=435
.Document.Body.InnerHTML = "<img src='\\10.10.67.173\Templates$\Scripts\Resources\loadingtest.gif'>"
End With
'Run the PS script
Set objShell = CreateObject("Wscript.shell")
objShell.Run "CMD /C START /B " & objShell.ExpandEnvironmentStrings("%SystemRoot%") & "\System32\WindowsPowerShell\v1.0\powershell.exe -executionpolicy bypass -file \\10.10.67.173\Templates$\Scripts\FormSignature-V0.9.5.ps1", 0, False
'Determine when to close Loading screen
Do While counter < 3
wscript.Sleep 2000
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colProcessList = objWMIService.ExecQuery _
("Select Name from Win32_Process WHERE Name LIKE '" & FindProc & "%'")
If colProcessList.count>0 then
'Quit the process if it finds its running
WScript.Echo("found")
'objExplorer.quit
else
'Do nothing
WScript.Echo("not found")
End if
Set objWMIService = Nothing
Set colProcessList = Nothing
counter = counter + 1
Loop
Set objShell = Nothing
In your VB script:
Create a file in an folder the PS script can access.
Launch your loading image.
Launch your PS script.
In your wait loop, every second or so, check if the file still exists.
If it does, close the instance of IE and exit your script.
In your PS script:
After your form initialization code is finished or the first action after the form load, locate and delete the file.

Starting a process in VBS: path not found

I need to make a simple vbs script to run some process' automatically. I found the following script on microsoft's website. It works fine to run notepad.exe the way the original example shows, but I'm trying to modify it to run myprog.exe. The full path to this program is: C:\myprogdir\myprog.exe
Const SW_NORMAL = 1
strComputer = "."
strCommand = "myprog.exe"
strPath = "C:\myprogdir\"
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" _
& strComputer & "\root\cimv2")
' Configure the Notepad process to show a window
Set objStartup = objWMIService.Get("Win32_ProcessStartup")
Set objConfig = objStartup.SpawnInstance_
objConfig.ShowWindow = SW_NORMAL
' Create Notepad process
Set objProcess = objWMIService.Get("Win32_Process")
intReturn = objProcess.Create _
(strCommand, strPath, objConfig, intProcessID)
If intReturn <> 0 Then
Wscript.Echo "Process could not be created." & _
vbNewLine & "Command line: " & strCommand & _
vbNewLine & "Return value: " & intReturn
Else
Wscript.Echo "Process created." & _
vbNewLine & "Command line: " & strCommand & _
vbNewLine & "Process ID: " & intProcessID
End If
I keep getting Return value: 9, which indicates "Path Not Found". However the path is correct. Is there something I'm not getting?
You don't need all that to start a process, you just need the Shell object. Also, be sure to wrap the path of your executable in quotes (in case the path has spaces). Like this:
Option Explicit
Dim shl
Set shl = CreateObject("Wscript.Shell")
Call shl.Run("""C:\myprogdir\myprog.exe""")
Set shl = Nothing
WScript.Quit
Unless the path to your program is included in the system's %PATH% environment variable you need to specify the commandline with the full path to the executable. Specifying the path just as the working directory will not work.
strProgram = "myprog.exe"
strPath = "C:\myprogdir"
Set fso = CreateObject("Scripting.FileSystemObject")
strCommand = fso.BuildPath(strPath, strProgram)
...
intReturn = objProcess.Create(strCommand, strPath, objConfig, intProcessID)
Using the BuildPath method will save you the headaches caused by having to keep track of leading/trailing backslashes.
Note that you need to put double quotes around a path that contains spaces, e.g. like this:
strCommand = Chr(34) & fso.BuildPath(strPath, strProgram) & Chr(34)
As others have already pointed out, there are simpler ways to start a process on the local computer, like Run:
Set sh = CreateObject("WScript.Shell")
sh.Run strCommand, 1, True
or ShellExecute:
Set app = CreateObject("Shell.Application")
app.ShellExecute strCommand, , strPath, , 1
There are some notable differences between Run and ShellExecute, though. The former can be run either synchronously or asynchronously (which means the command either does or doesn't wait for the external program to terminate). The latter OTOH always runs asynchronously (i.e. the method returns immediately without waiting for the external program to terminate), but has the advantage that it can be used to launch programs with elevated privileges when UAC is enabled by specifying the verb "runas" as the 4th argument.
However, these methods only allow for launching processes on the local computer. If you want to be able to launch processes on remote computers you will have to use WMI:
strComputer = "otherhost"
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" _
& strComputer & "\root\cimv2")
See here for more information about WMI connections to remote hosts.

Close an application using VBScript

I was trying to open and close an application.
I tried like this:
Dim App1
Set App1 = CreateObject("WScript.Shell")
App1.Run("firefox")
App1.Quit
Firefox will open, but it will not close.
Error message:
object doesn't support this property or method
I referred InDesign Scripting how to quit application (not document)
Please tell me the procedure to close the application.
If you want to be able to terminate a process that way you need to use the Exec method instead of the Run method.
Set ff = CreateObject("WScript.Shell").Exec("firefox")
'you do stuff
ff.Terminate
I observed a few ways:
taskkill - Worked only if I try to kill the same process, as I run.
Dim oShell : Set oShell = CreateObject("WScript.Shell")
oShell.Run """C:\My_Scripts\ddl.exe"" -p1 -c"
'some code
oShell.Run "taskkill /f /im ddl.exe", , True
SendKeys - Works for all app, if the window name is known.
Dim oShell : Set oShell = CreateObject("WScript.Shell")
filename = "C:\Some_file.txt - Notepad"
act = oShell.AppActivate(fileName)
oShell.SendKeys "% C"
WMI object - 2 ways above worked good for me so I didn't try it.
You can find an example here:
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\.\root\cimv2")
Set colProcessList = objWMIService.ExecQuery _
("Select * from Win32_Process Where Name = 'Chrome.exe'")
Set oShell = CreateObject("WScript.Shell")
For Each objProcess in colProcessList
oShell.Run "taskkill /im chrome.exe", , True
Next
Here is an alternative VBScript implementation:
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colProcessList = objWMIService.ExecQuery _
("Select * from Win32_Process Where Name = 'Notepad.exe'")
For Each objProcess in colProcessList
objProcess.Terminate()
Next
Firefox is not a COM object. There is no Firefox COM object. Firefox does not want you to use COM. Or NET. Or Microsoft. That is why you could not create a Firefox object, so you created a WScript.Shell object instead.
WScript.Shell does not have a quit method. If it did, it wouldn't help kill Firefox.
This is an example of using WMI from VBS to start, then kill a process like Firefox.
Good work for this example:
Dim oShell : Set oShell = CreateObject("WScript.Shell")
oShell.Run """C:\My_Scripts\ddl.exe"" -p1 -c"
'some code
oShell.Run "taskkill /f /im ddl.exe", , True

Resources