Not able to launch bat file form VBScript if path contains a space

╄→гoц情女王★ 提交于 2019-12-01 06:31:18

try like this:

Dim WshShell, strCurrentDirectory  
Set WshShell = CreateObject("WScript.Shell")  
strCurrentDirectory    = WshShell.CurrentDirectory  
WshShell.Run """" & strCurrentDirectory & "\di r\myFileToRun.bat" & """" , 0  
Set WshShell = Nothing

You just need to escape the quotes in the string correctly, the rule is whenever you want to show a quote in a string double it.

So, this command

WshShell.Run strCurrentDirectory & "\myFileToRun.bat" , 0

At the moment will be passed as;

D:\My Folder\batchfiles\myFileToRun.bat

As with most Windows programs paths with spaces need to be surrounded with quotes when passed to ensure the full path is recognised, at the moment Run() is seeing

D:\My

and the rest as an argument passed to the My program. As the system won't be able to find the My program it will cause the

System cannot find the file specified

error.

To fix this we need to pass a quoted string (doubling the quotes for each literal quote we want to include)

WshShell.Run """" & strCurrentDirectory & "\myFileToRun.bat""", 0

which will be passed as;

"D:\My Folder\batchfiles\myFileToRun.bat"

Note: When concatenating with variables we still need to open and close the string correctly. For a situation like above we concatenate the string """" on to a variable, which is simply "" but with a opening and closing quote to denote the literal string.

Also variables need to be correctly concatenated to the string or you will get weird results, for example your first attempt to escape the string

WshShell.Run """strCurrentDirectory & "\myFileToRun.bat" "", 0

would cause;

Expected end of statement

because it isn't a correctly terminated string.

You can use this function to add double quotes into variables :

Function DblQuote(Str)
    DblQuote = Chr(34) & Str & Chr(34)
End Function

So, the code becomes easy for reading :

Dim WshShell, strCurrentDirectory  
Set WshShell = CreateObject("WScript.Shell")  
strCurrentDirectory = WshShell.CurrentDirectory  
wscript.echo DblQuote(strCurrentDirectory & "\My Folder\myFileToRun.bat")
WshShell.Run DblQuote(strCurrentDirectory & "\My Folder\myFileToRun.bat"),0 
Set WshShell = Nothing
'********************************************************************
Function DblQuote(Str)
    DblQuote = Chr(34) & Str & Chr(34)
End Function
'********************************************************************
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!