VBScript: how to run a program from vbscript
I always need this one: how do you run a program from within VBScript? For example, you may need to launch notepad or wget from a VBScript. Here is the code to launch notepad:
sub shell(cmd)
' Run a command as if you were running from the command line
dim objShell
Set objShell = WScript.CreateObject( "WScript.Shell" )
objShell.Run(cmd)
Set objShell = Nothing
end sub
shell "notepad"
Put that in a text file called "run_notepad.vbs", doubleclick it, and notepad will run. This may not seem too useful, but imagine that you use VBScript to run a series of WGETs, for example, based on input from SQL Server.
UPDATE
I have had a lot of requests for enhancements to this program. The following is the cadillac version. It calls an EXE and asks the user for parameters to pass to the EXE.
sub shell(cmd)
' Run a command as if you were running from the command line
dim objShell
Set objShell = WScript.CreateObject( "WScript.Shell" )
objShell.Run(cmd)
Set objShell = Nothing
end sub
dim file_name
' Ask the user for a parameter
file_name = inputbox("What file to see?", "File name?", "c:\boot.ini")
if file_name <> "" then
' The user gave the parameter. Open the program
' with the value the user gave.
shell "C:\WINNT\system32\notepad.exe " & file_name
else
msgbox "User cancelled.", 16, "User cancelled"
end if
how do you get the script to open a text file using notepad?
ReplyDeleteshell "notepad test.txt"
DeleteWilliam,
ReplyDeleteChange the last line to include the filename to open:
shell "notepad c:\test\test_text.txt"
Hey I just wanted to leave a little comment to say that I found the code in this post very useful, so thanks for that :)
ReplyDeleteCan this script be modified to run a .exe file? Also can it be set up to accept the default choices with running the .exe?
ReplyDeleteAnonymous,
ReplyDeleteYes, you can launch an EXE and give it parameters. In fact, the example given here launches an EXE. Here is an example that more explicitly calls an EXE and gives it parameters:
sub shell(cmd)
' Run a command as if you were running from the command line
dim objShell
Set objShell = WScript.CreateObject( "WScript.Shell" )
objShell.Run(cmd)
Set objShell = Nothing
end sub
shell "C:\WINNT\system32\notepad.exe c:\boot.ini"
The following is the cadillac version. It asks the user to provide the parameter for the EXE you want to launch:
sub shell(cmd)
' Run a command as if you were running from the command line
dim objShell
Set objShell = WScript.CreateObject( "WScript.Shell" )
objShell.Run(cmd)
Set objShell = Nothing
end sub
dim file_name
' Ask the user for a parameter
file_name = inputbox("What file to see?", "File name?", "c:\boot.ini")
if file_name <> "" then
' The user gave the parameter. Open the program
' with the value the user gave.
shell "C:\WINNT\system32\notepad.exe " & file_name
else
msgbox "User cancelled.", 16, "User cancelled"
end if
In any case, you can replace C:\WINNT\system32\notepad.exe with the EXE you want to launch, and include parameters.
Email if you have any more questions: TimothyChenAllen@gmail.com
Hi Tim - thank you for sharing your knowledge. I'd like to launch an executable with paramaters, but without any user intervention. Is that possible?
ReplyDeleteThx again
(dig the tunes brother! got some of mine up @ http://www.tylerswire.com)
- Tyler
Tyler,
ReplyDeleteThe non-cadillac version in the original post will work. The trick is to put the parameters after the program name, like so:
shell "notepad c:\test_file.txt"
If you need to run the program without having the user double-click it (for example, run it from the scheduler), you can run it from the command line by using CSCRIPT:
c:\>cscript launcher.vbs
Thanks for the comment on the music-- I'm listening to yours now. Wow, you're good! Really clean-- if there's one thing I'd like to do better, it would be to get my production a lot cleaner. I guess if I'd actually invest in a microphone... one of these days. Anyway, you've got good tunes, you should be proud of that.
Guess if I'da read through the post a bit more I'da seen where you already answered this question :) Sorry for that & thx for the response.
ReplyDeleteThat album was actually recorded completely acoustic through the air... into one of those white straw mics. The key was the sound card. At the time, I happened to be using and old PCI Sound Blaster Live card. You can probably get on one craigslist.org for $5. Because I'm laptop based now... and there's no room for a PCI card... I just recently purchased one of these... http://www.amazon.com/Creative-Labs-SB1090-Blaster-Surround/dp/B0017QQQAE and it does just as good if not better. Still using the old white straw mic I've had since 1998 :)
Take Care -
- Tyler
Tyler, how cool! Thanks for the advice-- I had no idea that a USB-port sound card was available. I am laptop-based, too-- I'm married with a kid, so my "recording studio" is our apartment building's party room. So I lug the laptop down there to record. I will be buying one of these! Thanks for the advice!
ReplyDeletePersonally I'd spend a little more cash and get yourself an EMU audio interface. Some complain about EMU but for the price they're pretty good. I've had a PCI EMU 0404 card for years without a problem. I think the cheapest is the EMU 0202:
ReplyDelete[amazon.com]
It comes with a better selection of I/O that the Creative, including a balanced XLR mic port. More expensive versions come with a greater selection of inputs and outputs as well as MIDI ports.
Just something to think about :)
Oh and the only thing to watch out for is USB power. It shouldn't be a problem these days but all my old Dell laptops won't power any of my USB midi keyboards as they don't give out enough current. If that were the case you can still get yourself a PCMCIA audio interface with a break-out box for all you audio I/O.
Thanks, GG. Come to think of it, my (ancient) laptop doesn't have USB 2.0 ports. So the newer adapters may not work for me. I'll check it out; I'm kind of tired of all my recordings starting out with a rush of white noise from my laptop.
ReplyDeleteHi Tim, I came for a peek at your code...and stayed for the music. Your songs have touched me. Thank you :)
ReplyDeleteKathi, thanks so much! Sometimes I wonder if I should keep doing this, especially since I have no idea what I'm going to do with all of these songs. I still have to put out this week's song-- I'm in Albuquerque without a guitar, so I guess this one will be a Capella.
ReplyDeleteAny idea how to execute this program with switches and paramaters?
ReplyDeleteI can't get it to work for nothing.
Here is the command:
"C:\Program Files\DAEMON Tools Lite\daemon.exe" -mount 0, "D:\Test\Test.iso"
The command works fine from Command Prompt and from Run Dialog Box.
Just can't get it to work in a VBScript.
I've also tried:
Set objShell = CreateObject("Shell.Application")
objShell.ShellExecute(cmd).
But I have been unlucky.
Using the command:
"C:\Program Files\DAEMON Tools Lite\daemon.exe"
works fine.
I just can't get the syntax of switches correct.
Thanks
Omar, the problem is probably the quote marks ("). In VBScript, to make a quote appear in a string, you have to put two quotes (""). Here is the simple version script with your command:
ReplyDeletesub shell(cmd)
' Run a command as if you were running from the command line
dim objShell
Set objShell = WScript.CreateObject( "WScript.Shell" )
objShell.Run(cmd)
Set objShell = Nothing
end sub
shell """C:\Program Files\DAEMON Tools Lite\daemon.exe"" -mount 0, ""D:\Test\Test.iso"""
I hope that works. If it doesn't, please email me at TimothyChenAllen@gmail.com with the error message, and I'll see what I can do. Thanks!
Thanks. Your solution worked like a charm.
ReplyDeleteI am trying to use the .Run method with the arguments. how would I do this with your code please?
ReplyDeleteobject.Run(strCommand, [intWindowStyle], [bWaitOnReturn])
I need to say something like objShell(cmd,1,True), but compiling bombs when I try that.
Thanks
Hey Tim, I know these posts are kindda old but was hoping you could get me some material to study VBScript? Like VBS for dummies? LOL I am really intrested in creating a little robot to run a couple of reports for me at work, but just can't seem to make it start. The middle part is easy as I can make this program record it's own VBScript and just paste it within the macro, but I have no clue how to start it.
ReplyDeleteMy email is girl_yes@yahoo.com thanks in advance
Hi Tim
ReplyDeleteI'm hoping you can help, I have a similar situation as to Omar's and I can't seem to get it working, the single line command works fine in CMD which is:
D:\ITTools\PsExec.exe \\ -c D:\ITTools\notepadstop.bat
I tried this but seems to try to execute PsExec in interactive mode and can't get it working
sub shell(cmd)
' Run a command as if you were running from the command line
dim objShell
Set objShell = WScript.CreateObject( "WScript.Shell" )
objShell.Run(cmd)
Set objShell = Nothing
end sub
shell """D:\ITTools\PsExec.exe"" \\rpc13124, ""-c D:\ITTools\notepadstop.bat"""
Thanks
Steve
Steve, try this:
Deletesub shell(cmd)
' Run a command as if you were running from the command line
dim objShell
Set objShell = WScript.CreateObject( "WScript.Shell" )
objShell.Run(cmd)
Set objShell = Nothing
end sub
shell "D:\ITTools\PsExec.exe \\rpc13124 -c D:\ITTools\notepadstop.bat"
As far as I can tell, you don't need all of the extra quotes, unless you are using a variable to specify the network address. If that is the case, you could do something like this:
sub shell(cmd)
' Run a command as if you were running from the command line
dim objShell
Set objShell = WScript.CreateObject( "WScript.Shell" )
objShell.Run(cmd)
Set objShell = Nothing
end sub
network_name = "\\rpc13124"
shell "D:\ITTools\PsExec.exe " & network_name & " -c D:\ITTools\notepadstop.bat"
A good debugging trick with this is to change the last line to:
msgbox "D:\ITTools\PsExec.exe " & network_name & " -c D:\ITTools\notepadstop.bat"
Then, run the program and look at the output. If it looks like the command line you want, change "msgbox" back to "shell" and it should run correctly. Good luck!
i have script to backup dump database..
ReplyDeletehow script to know the process was 100% completed and continue to another process ..
this is my script
sub shell(cmd)
' Run a command as if you were running from the command line
dim objShell
Set objShell = WScript.CreateObject( "WScript.Shell" )
objShell.Run(cmd)
Set objShell = Nothing
end sub
shell "exp pass/pass@192.168.0.117:1521/orcl FILE=D:\DUMP_DATABASE\apps_v2\apps_database.dmp"
'next process
shell "C:\"Program Files\WinSCP\WinSCP.com" /command "open apps_v2" "synchronize remote D:\DUMP_DATABASE\apps_v2 DATABASE/" exit""
Ucup, you want to make the command run *modally*. That can be done, it requires a slight modification of the script:
Deletesub shell(cmd, wait)
' Run a command as if you were running from the command line
dim objShell
Set objShell = WScript.CreateObject( "WScript.Shell" )
objShell.Run cmd, , wait
Set objShell = Nothing
end sub
shell "exp pass/pass@192.168.0.117:1521/orcl FILE=D:\DUMP_DATABASE\apps_v2\apps_database.dmp", true
'next process
shell "C:\"Program Files\WinSCP\WinSCP.com" /command "open apps_v2" "synchronize remote D:\DUMP_DATABASE\apps_v2 DATABASE/" exit"", false
Notice that I put an extra parameter ("wait") in the command call, and put either true or false after the call to shell (true means wait for the command to finish). Enjoy.
Hi Timothy,
ReplyDeleteI have a scenario where I need to restart an application twice a week at 2 am. This application needs a userid and password to login. So I created a vb script which will close the application, load it, give userid and password, login and then minimize the window. And I created a scheduled task to call this script. This is in a server which runs 24X7.
Issue is, it works fine if it is running when I am logged in. But when I am not logged in, it just loads the application and stops there. It neither enters the credentials nor login. Seems some focussing issue. Could u help?
Here is my script.
Dim oShell
set oShell= Wscript.CreateObject("WScript.Shell")
oShell.Run "MyApp.exe"
WScript.Sleep 2000
oShell.Sendkeys "userid"
oShell.SendKeys("{Tab}")
WScript.Sleep 1000
oShell.Sendkeys "password"
WScript.Sleep 1000
oShell.SendKeys("{Enter}")
oShell.SendKeys "% n"
Wscript.Quit
Hi Bin,
DeleteI don't think VBScript will work for this. I worked on something like this before; basically, for you to be able to do sendkeys, you need a session. Sorry, I wish I had better news.
Hi Timothy,
ReplyDeleteThank you very much for your post. I'm new to scripting, unfortunately, and I have not been successful in modifying your script to work with my particular program. I would greatly appreciate it if you would assist me in correcting whatever I've done wrong. Normally, I would go to the directory C:\Program Files (x86)\Interwoven\WorkSite, then type: addiman.exe ws1. Below is what I've modified from your example. Thank you so much!!
sub shell(cmd)
' Run a command as if you were running from the command line
dim objShell
Set objShell = WScript.CreateObject( "WScript.Shell" )
objShell.Run(cmd)
Set objShell = Nothing
end sub
shell ""C:\Program Files (x86)\Interwoven\WorkSite\addiman.exe WS1""
end if
Sam, try this. I think the problem was the quote marks were off, and you don't need the last line (end if):
Deletesub shell(cmd)
' Run a command as if you were running from the command line
dim objShell
Set objShell = WScript.CreateObject( "WScript.Shell" )
objShell.Run(cmd)
Set objShell = Nothing
end sub
shell """C:\Program Files (x86)\Interwoven\WorkSite\addiman.exe"" WS1"
Thank you so much, Timothy!!
DeleteDear Timothy, I'm sorry to trouble you once more about the script. Is "shell(cmd)" able to run as an administrator? Unfortunately, the addiman.exe requires the cmd run as an administrator. But what's weird is that it works intermittently. In addition, I've included a few other commands to the script. (Outlook must close first in order for the other two EXEs to install.) If you have the time, would you please review and let me know what I've done wrong? Thank you very much - your help has been invaluable!!
ReplyDeleteWScript.Sleep 20000
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colProcessList = objWMIService.ExecQuery _
("Select * from Win32_Process Where Name = 'Outlook.exe'")
For Each objProcess in colProcessList
Set objOutlook = CreateObject("Outlook.Application")
objOutlook.Quit
Next
WScript.Sleep 20000
sub shell(cmd)
' Run a command as if you were running from the command line
dim objShell
Set objShell = WScript.CreateObject( "WScript.Shell" )
objShell.Run(cmd)
Set objShell = Nothing
end sub
shell """C:\Program Files (x86)\Interwoven\WorkSite\addiman.exe"" WS1"
WScript.Sleep 30000
sub shell(cmd)
' Run a command as if you were running from the command line
dim objShell
Set objShell = WScript.CreateObject( "WScript.Shell" )
objShell.Run(cmd)
Set objShell = Nothing
end sub
shell "\\fs01\Deployments\ContactEase\SyncUser\setup.exe"
Hi timothy, i read your blog and i hope you can help me to figure the script...im still new for scripting
ReplyDeletemy boss tell me to build some script to run .vbs from another server with vbscript too, i try this code :
Dim WSHShell
'WSHShell = CreateObject("Wscript.Shell")
'WSHShell.Run("""C:\Windows\System32\CScript.exe"" ""\\PL-SV-CRE-02\C:\Automail\RunExcel - Excel-Newconn.vbs""")
but it doesn't work anything, i'll try this code too
Dim WshShell
Dim strScriptPath
WshShell = CreateObject("WScript.Shell")
strScriptPath = "\\PL-SV-CRE-02\C:\Automail\RunExcel - Excel-Newconn.vbs"
WshShell.Run("wscript.exe " & Chr(34) & strScriptPath & Chr(34), 1, vbTrue)
and it's same doesn't work, can you help me...thank you so much timothy..
My script won't do that, but there are a couple of command-line commands that will. AT (http://ss64.com/nt/at.html) and SCHTASKS (http://technet.microsoft.com/en-us/library/cc725744.aspx#BKMK_now) may be helpful. There is also a way to do this if you have access to POWERSHELL (http://www.howtogeek.com/117192/). One idea that occurs to me is that you may be able to create a task using the task scheduler on the remote PC, then use SCHTASKS RUN to make the task run from another PC. I wish I could help you more on this, but I don't have two PCs I can check this out on. Good luck; let me know how it goes!
Deletehmm, actually i want to run the code on the Jobs sql, after the other task is finished then i call/run the vbs, so after the step 1 is finished and then call/run the vbs,,
ReplyDelete