如果 path/name 包含 space,则系统无法找到该文件

The system cannot find the file if its path/name contains a space

Path = split(wscript.scriptFullName, wscript.scriptname)(0) 
CreateObject("wscript.shell").run(Path & "Name.txt")

如果文件路径和文件名都不包含 space,则上述脚本可以正常工作。

如果其中一个包含 space,结果将为;

Error: The system cannot find the file specified.

如何修复错误?

CreateObject("wscript.shell").run(""""Path & "Name.txt""")

是这样。

规则相当简单:

  1. 所有字符串都必须以双引号开头和结尾才能成为有效字符串。

    Dim a
    a = "Hello World" 'Valid string.
    a = "Hello World  'Not valid and will produce an error.
    
  2. 任何变量的使用都必须使用 String Concatenation 字符 & 将它们与字符串组合。

    Dim a: a = "Hello"
    Dim b
    b = a & " World" 'Valid concatenated string.
    b = a " World"   'Not valid and will produce an error.
    
  3. 由于双引号用于定义字符串,因此字符串中所有双引号实例都必须通过双引号进行转义"",但规则 1. 仍然适用。

    Dim a: a = "Hello"
    Dim b
    b = """" & a & " World""" 'Valid escaped string.
    b = """ & a & " World"""  'Not valid, start of string is not complete 
                              'after escaping the double quote 
                              'producing an error.
    

遵循这三个规则,你就不会出错。

考虑到这些,上面的行需要是;

CreateObject("wscript.shell").run("""" & Path & "Name.txt""") 

生成一个用双引号括起来的字符串。


有用的链接

  • VBS with Space in File Path
  • Adding quotes to a string in VBScript
  • (更多关于字符串连接).