VBScript中变量嵌入文件路径报‘path not found’错误求助
问题解决:VBScript路径找不到错误
你遇到的问题核心是:VBScript不会自动识别字符串里的[strUser]作为变量引用,系统会把它当成路径的字面部分,实际查找的路径是C:\Users\[strUser]\Downloads\startup.vbs——这个路径不存在,所以触发“path not found”错误。
修正方法1:字符串拼接(最直接)
用&符号把变量和固定字符串拼接,让用户名变量值替换到路径中:
dim strUser strUser = CreateObject("WScript.Network").UserName dim filesys set filesys=CreateObject("Scripting.FileSystemObject") filesys.CopyFile "C:\Users\" & strUser & "\Downloads\startup.vbs", "C:\Users\" & strUser & "\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\"
修正方法2:Replace函数替换占位符
如果习惯用占位符写法,可以先用Replace函数把字符串里的[strUser]替换成实际用户名:
dim strUser strUser = CreateObject("WScript.Network").UserName dim sourcePath, targetPath sourcePath = Replace("C:\Users\[strUser]\Downloads\startup.vbs", "[strUser]", strUser) targetPath = Replace("C:\Users\[strUser]\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\", "[strUser]", strUser) dim filesys set filesys=CreateObject("Scripting.FileSystemObject") filesys.CopyFile sourcePath, targetPath
进阶优化:用系统特殊文件夹获取路径(更可靠)
硬编码路径可能在不同系统版本出问题,建议用WScript.Shell的SpecialFolders获取系统预设文件夹路径,比如Startup目录:
dim wshShell, strUser set wshShell = CreateObject("WScript.Shell") strUser = CreateObject("WScript.Network").UserName ' 获取系统Startup目录 dim startupPath startupPath = wshShell.SpecialFolders("Startup") ' 拼接Downloads路径 dim downloadPath downloadPath = "C:\Users\" & strUser & "\Downloads\startup.vbs" dim filesys set filesys=CreateObject("Scripting.FileSystemObject") filesys.CopyFile downloadPath, startupPath & "\"
内容的提问来源于stack exchange,提问作者Robinalex
相关产品推荐
相关产品推荐

