Executing an EXE inside a VBScript file that has spaces in the path.

I've done quite a bit of scripting but ran across something that baffles me.  Trying to execute a file in a directory with a spaces in the path would bomb.  I googled and found a thing that has me put [] inside to fix it but it didn't work.  Here is what i was trying to do, if there is no spaces in the path to the EXE including any directories, the script works fine.   Here is an example to a path for an EXE c:\winnt\system32\Ica PassThrough\pn.exe.  Here is the script code

Set wshShell = WScript.CreateObject ("WSCript.shell")
wshshell.run "c:\winnt\system32\Ica PassThrough\pn.exe", 6, True
set wshshell = nothing

Of course, this code would BOMB!  The script would return an error complaining it couldn't find the file.    Thanks to quick posting in the news://msnews.microsoft.public.windows.server.scripting newsgroup. 

Al Dunbar, world famous fellow MVP posted the answer to my prayers!

Your .run command is trying to run something called "C:\winnt\system32\ica" and pass it a parameter called "PassThrough\pn.exe". This is the same thing you would get if you typed the following at a command prompt:

    c:\winnt\system32\Ica PassThrough\pn.exe

If the name of the file to run is actually "c:\winnt\system32\Ica PassThrough\pn.exe", you would enter it at the command prompt as:

    "c:\winnt\system32\Ica PassThrough\pn.exe"

The double quotes in your code do not form part of the filename string being passed to the .run method, they are required to indicate a literal string.
You can prove this is the case by changing your script to look like this:

> Set wshShell = WScript.CreateObject ("WSCript.shell")
> wshshell.run c:\winnt\system32\Ica PassThrough\pn.exe, 6, True
> set wshshell = nothing


Which will throw a syntax error (for rather obvious reasons). You need to pass a string that actually contains the quoted filename, which can be done this way:

> wshshell.run """c:\winnt\system32\Ica PassThrough\pn.exe""", 6, True

Within a literal string, a single double-quote character is represented by two double-quote characters.   Notice the Three double quotes around the string,  This worked!  Thought I'd pass this tip along.

42 Comments

  • Greg P. said

    Thanks! This solved the exact same problem for me! I was really hung up on this because I was testing for a file existance with:
    <br>
    <br>objFSO.FileExists()
    <br>
    <br>And that worked, WITH the spaces, yet running the file:
    <br>
    <br>WshShell.Run()
    <br>
    <br>Does not. I understand now why, but it's really inconsistant the way this works. In Real VB, you have an extra paramater in the shell function that is for the commandline parms. In this example, it's all one string... Way to go M$..
    <br>
    <br>Anyway, thanks so much for posting this!
    <br>-Greg
    <br>

  • Steve Schofield said

    Glad this worked for ya. This is very flakey why you have to put 3 quotes on each side. The wierd i couldn't get to work with my scenerio is using the dos name.

  • http:// said

    Thanks for posting this info.
    <br>I had resorted to using the dir /x command to get the 8dot3 filename representation of each component in the path and substituting that into my script. It works but looks pretty ugly.
    <br>
    <br>One additional wrinkle though. If you are passing additional parameters to the command to be run then you must remember to put the closing &quot;&quot; after the executable name and the final &quot; after the command line parameters.
    <br>
    <br>Yes it's obvious when you know.

  • http:// said

    Here's what I do to get around the quoting issue when passing parameters:
    <br>
    <br>strCmd = &quot;somepath\file.exe &quot;
    <br>strCmd = strCmd &amp; chr(34) &amp; myParm &amp; chr(34)
    <br>
    <br>Using this method you can build rather complex paramaters yet easily troubleshoot them.
    <br>
    <br>Cheers,
    <br>
    <br>Jeff

  • http:// said

    In my situation, I had to run an import command... so basically, had to call an exe, in a folder with spaces, with a couple command line switches, and an INI file in a location with spaces. I ended up breaking apart the command line into sections. I was going to do the 8.3 Char names, but it looked to ugly for my tastes. So, here's what I did...

    Example:
    CmdLine1 = """C:\Program Files\Some Location\More Spaces\The.exe"
    CmdLine2 = "/s /i"
    CmdLine3 = """C:\Program Files\Location to Ini\More Spaces\The INI File Name.ini"""
    CmdLine = CmdLine1 & " " CmdLine2 & CmdLine3
    Wshell.Run CmdLine,1,True

    Hope that helps someone...
    -Steve J

  • http:// said

    Well thats nice but
    if something like that happens:

    for each f in files
    .....
    Wshell.Run <somepath>&f
    .....
    next

    and in f - spaces exists, example "win dos.exe"
    what to do than. How could I insert double " in f variable?????????????????????????????????????????


  • Mark said

    Thanks for the info. This was driving me nuts until I found your post. Also, to pass switches I found you also have to do an &. Like this:

    WshShell.Run """C:\Program Files\RivaTuner v2.0 Final Release\RivaTuner.exe""" & "/S", 1

    Notice the "/S" switch.

  • http:// said

    Jeff -

    Ive been stuck trying to pass parameters forever - finally got it today.

    Thanks

    I dont understand why the chr(34) works in place of a space but it does so I am happy.

  • Uri said

    <P>We just had a related issue when using an ActiveX VBScript task with SQL Server 2000 DTS package.</P>
    <P>The command we wanted to run was called log.vbs.</P>
    <P>cmd = "\\unc\without\spaces\log \\unc\to\logfile\file.log ""Message to appear in the logfile"""</P>
    <P>So here we have an argument that itself requires double-quotes, namely the contents of the log entry must be enclosed by double quotes. &nbsp;The first weirdness was that the script had to have the .vbs extension before it would run using WshShell.Run, even though it ran fine on the command-line without it. &nbsp;The solution ended up looking like so:</P>
    <P>cmd="""\\unc\without\spaces\log.vbs"" \\unc\to\logfile\file.log "</P>
    <P>msg = Now () &amp; f.name &amp; " file processed"</P>
    <P>cmd = cmd &amp; Chr(34) &amp; msg &amp; Chr(34)</P>
    <P>WshShell.Run cmd, 1, True</P>
    <P>Anyway, this thread helped us so we wanted to contribute for others.</P>

  • http:// said

    Why wouldn't this create the text file at the end. It runs but somehow ignore ">> C:\Policies\ListAllGPOs.txt" part

    Set shell = CreateObject("WScript.Shell")
    shell.Run "C:\Policies\ListAllGPOs.wsf >> C:\Policies\ListAllGPOs.txt"

  • http:// said

    the >> does not work because you need %comspec% /c in there so it would be:

    Set shell = CreateObject("WScript.Shell")
    shell.Run "%comspec% /c C:\Policies\ListAllGPOs.wsf >> C:\Policies\ListAllGPOs.txt"

    That should do it for ya.

    -Mike

  • http:// said

    Thanks, I ran into exactly this problem. I knew it had something to do with the string literal, but I couldn't remember the syntax to escape a double quote in VBScript (three double-quotes? four?). Your web page answered it when the MS Scripting documentation did not!

  • http:// said

    Also try this..

    Copy the path to the 'Path' variable in the Environment variables and run the .exe directly w/o giving any path.

    For eg:
    Set wshShell = WScript.CreateObject ("WSCript.shell")
    > wshshell.run "pn.exe", 6, True
    > set wshshell = nothing

    and add the Path "c:\winnt\system32\Ica PassThrough\" to the environment variable

  • http:// said

    I have to run one batch file.
    and need to display its output.


    Set wshShell = WScript.CreateObject("WSCript.shell")
    strExec1 = "C:\Program Files\Operations"
    strExec2 = "C:\Program Files\Operations\rap.bat"
    set owshshell = wshshell.run(start&" "&strExec1&" "&strExec2)
    Wscript.Echo(owshshell.StdOut.ReadAll())


    What is the problem in this.
    I tried with wshshell.exec also.

  • http:// said

    <P>I had exactly the same problem running an executable and although the fix seems odd, it works fine!</P>

  • http:// said

    <P>cmd = """c:\program files\winrar\winrar.exe"" a " &amp; ZIPPATH &amp; BackupFileName &amp; " " &amp; &nbsp;PATHNAME &amp; FILE &amp; "*.xls"</P>
    <P>where my FILE = weekly stylewise designwise2007-11-02</P>
    <P>I am using this in VB script but got an error </P>
    <P>! &nbsp; D:\Hemant\XP_SMTP_SendMail20071102.rar: Cannot open D:\Hemant\weekly</P>
    <P>! &nbsp; The system cannot find the file specified.</P>
    <P>! &nbsp; D:\Hemant\XP_SMTP_SendMail20071102.rar: Cannot open storewise</P>
    <P>! &nbsp; The system cannot find the file specified.</P>
    <P>! &nbsp; D:\Hemant\XP_SMTP_SendMail20071102.rar: Cannot open stylewise</P>
    <P>! &nbsp; The system cannot find the file specified.</P>
    <P>! &nbsp; D:\Hemant\XP_SMTP_SendMail20071102.rar: Cannot open designwise2007-11-</P>
    <P>! &nbsp; The system cannot find the file specified.</P>
    <P>Can anybody help me out with this i.e. how to zip a file having spaces in the name or how to remove the spaces form the file name?</P>

  • You saved Me!! said

    thanks sooooooo much for this amazing tip!!
    it really helped me!
    that error was bugging me for ages but as soon as i did your tip it worked!!!
    thanks again!!

  • Voodo_VBS said

    The original post hit the nail right on the head about the problem but failed to propose or seek an adequate resolution. Most of the other answers require knowledge of the original string structure and use specific concatenation construction of the same orginal string. So these answers are specific to each particular string rather and cannot be applied in a a general since strings could be anything with any amount of spaces in between and quotes in between.

    The goal is to wrap all of the expression in between quotes and then pass it with quotes surrounding it to the shell.run for execution as if you were typing it with on the command line including quotes at beginning and at end of the command. So here is the general answer. I am sure you will understand why 4 quotes are necessary i.e. two quotes between quotes always resolve to one passed along

    varExpression="Whatever command name with any spaces anywhere within it.exe or .bat"

    Set oWShell = CreateObject"WScript.Shell")
    strCommand = VarExpression
    'Test your result to the screen
    wscript.echo """" & strCommand & """"
    Call oWShell.Run ("""" & strCommand & """")
    Set oWShell = Nothing

  • vimal said

    i need to open a exe file in the back ground and open an internal link in the exe application can anyone help this

  • Amirali said

    THIS IS THE SCRIPT

    Set WshShell = WScript.CreateObject("WScript.Shell")
    WshShell.Run """c:\Newfolder\game.exe""",6,True
    set Wshshell = nothing

    I GET ERROR AS "THE SYSTEM CANNOT FIND THE FILE SPECIFIED"

    PLEASE HELP

  • Mike said

    There is another way to handle filepaths with spaces. Simply remove the space and add the ~1 after the name. If the directory name is longer than 6 characters you will only use the first 6 characters of the path followed by the ~1.

    Example:
    "C:\Documents and Settings\All Users\My Documents\"

    Is the same as this without the quotes.
    C:\Docume~1\AllUse~1\MyDocu~1

    If there are multiple directories with the same first 6 characters (i.e. c:\progra~1\micros~1...) you can increment the number to represent the folder you want. On my machine Microsoft Office is the 6th Microsoft application in Program Files and can be reached using the syntax below.

    c:\progra~1\micros~6

  • Craig said

    Hey guys, this is an awesome forum.. I think what most people are trying to do is pass parameters to .exe's and possibly parameters to MSI's within the exe's.. This JUST worked for me and its for both. And its been a combination of comments on here and other places. I hope this works for someone to!!

    wshshell.run ("""C:\Program Files\Packages\Interwoven\FileSite\Setup.exe""/S /V/qb"),1,True

    This script

    1) Enables the EXE to have spaces in the path, thus the three """ at each end. (Which include the switches)

    2) It Passes the silent switch /S to the .exe.

    3) Brackets at each end allow the space between /S /V and the statement to be consolidated integrating the /qb to be passed to the MSI..

    I used capitals also with the .exe as it is an installshield installer.. Hope this helps someone..

  • Chris said

    Hi All,

    I can't get this to work. I am using a stored argument in the switch. The stored argument may have spaces in it because it is a file absolute path. I can't figure out how to wrap it in quotes? Any suggestions?

    Set fso = CreateObject("Scripting.FileSystemObject")
    If WScript.Arguments.Count = 0 Then
    WScript.Echo "'Drag and Drop' file to fax"
    WScript.Quit
    End If

    'Pulls FileName Path stored in Argument Item(0) and puts it into the variable name strFilePath
    strFilePath = Wscript.Arguments.Item(0)

    'Get Fax Number
    FaxNumber=InputBox("Fax To:")

    Dim oShell
    Set oShell = WScript.CreateObject ("WScript.Shell")
    OL = """C:\Program Files (x86)\Microsoft Office\Office12\OUTLOOK.EXE"""
    Switch = " /c ipm.note /m "
    FaxProvider = "@greenfax.com"
    AttachSwitch = " /a "
    oShell.run (OL & Switch & FaxNumber & FaxProvider & AttachSwitch & strFilePath)

    Set oShell = Nothing

  • Matt said

    Hi, I am trying to have a script that would prompt for user's input twice and then use that input as part of the command line switches when running in the executable. To illustrate my example:

    The command that needs to run is:

    E:\SBAdmin\SbAdmCl.exe -Command:CleanupMachineGroup -Adminuser:SBAdmin -Adminpwd:&adminpw -Group:"& dbname &" -Database:"Safeboot Administration Database"

    Note that the switch has got two places where double quotes are required (the group name and the database name). This is where I struggle with the solution as those quotes seem to cause all the issues.
    Tried writing a script with PS, but it didn't like the -command work in the switch.

  • Karl said

    I tried "Voodo_VBS" code but was unable to get it to work.

    Dim wz_cmd
    Dim strCommand
    Dim ZipFile
    ZipFile = "C:\test data\test\test.ZIP"
    Dim ZipLoc
    ZipLoc = "C:\test data\test"

    wz_cmd = "C:\Program Files\WinZip\WZUNZIP.EXE -e " & ZipFile & " " & ZipLoc
    strCommand = wz_cmd
    wscript.echo """" & strCommand & """"
    Set oWShell = CreateObject("WScript.Shell")
    Call oWShell.Run("""" & strCommand & """")
    Set oWShell = Nothing

  • PaulCheese said

    Great thread! still going strong too, really helpfull.

    But ... I am trying to do a similar thing, but open up a shared printer queue.

    From start/run typing \\server\queuename works fine, but I can get no combination of quotes to work without the error '\\server\queuename is not accesable. you might not have permission etc'

    I have full permission on this share, and the local computer, but still nothing!

    The nearest I have got (code mainly copied from someone else, then modified)
    ---------------------------
    Option Explicit
    Const vbNormalFocus = 1
    Const PathToOpen = "\\server"
    Const Q = "\ReceptionReports"

    WScript.CreateObject("WScript.Shell").Run _
    "explorer.exe /n,/root,""" & PathToOpen & Q & """", vbNormalFocus
    ------------------------

    At this point I am lost, any suggestions please?

    Paul

  • Sanny Omar said

    Thank you. This was a big help. I spent several hours trying to figure out why my code wouldn't run until I found this website.

  • Udaynag said

    Great thread. I am trying to do a similar thing, but unable to get it work. I have a program that I want to run from a vb scipt with filenames as arguments in the command line, something like below.



    %Executable% -Exec %Algorithm% -Input Inp=0 File=%RefFile% Inp=1 File=%TestFile% %Settings% -Out %OutFile% -Append

    The line runs the executable with Algorithm that has RefFile and TestFile as inputs and updates the OutFile (Xls) with the result. I am trying to insert this into a vb script, so I don't have to call the batch file again. I followed a few suggestions in the thread, but none of them work.Any help is appreciated

  • kesepalli said

    I tried various option(double quotes,chr(34)...) to run my command where path is having the spaces by vbscript.Please find my code below
    Dim wsh
    Dim cmm1
    Dim cmm4
    Dim cmm5
    cmm1="cd C:\Program Files\Microsoft Visual Studio 10.0\VC"
    cmm4="vcvarsall.bat"
    cmm5="devenv C:\Myapp\My solutionfolder\myapp.sln /build"
    set wsh=WScript.CreateObject("WScript.shell")
    wsh.run "cmd /k" & cmm1 & "&&" & cmm4 & "&&" & cmm5
    set wsh=nothing

    when there is no path it will build the solution. If the path is having the space then i am getting error .. please anyone can help on this...

  • kevin said

    ya its working well thanks a lot, but i have one more problem that is Inside the same directory i want to execute anothe onr .cmd file, how can i do that? any one help.

Add a Comment