Problem copying files through xcopy using VBScript

孤者浪人 提交于 2019-12-11 07:01:48

问题


I am using VBScript to copy files using xcopy. The problem is that the folder path has to be entered by the user. Assuming I put that path in a variable, say h, how do I use this variable in the xcopy command?

Here is the code I tried:

Dim WshShell, oExec, g, h
h = "D:\newfolder"

g = "xcopy $h D:\y\ /E"
Set WshShell = CreateObject("WScript.Shell")

Set oExec = WshShell.Exec(g)

I also tried &h but it did not work. Could anyone help me work out the correct syntax? Any help is appreciated.


回答1:


The problem may be that you are not using quotes properly. Try this

Dim WshShell, oExec,g,h 
h= Chr(34) & "D:\newfolder" & Chr(34)
g="xcopy " & h & " " & Chr(34) & "D:\y\" & Chr(34) & " /E"
Set WshShell = CreateObject("WScript.Shell")

Set oExec = WshShell.Exec(g)

If there are spaces in either path the path must be contained in quotes, Chr(34) is the quote character so by inserting them at the beginning and end of the path it wraps the paths in quotes.

Lets say the source path is C:\Documents and Settings. If you pass that to xcopy it will think the source is 'C:\Documents' the destination will be 'and' and the arguments will be 'Settings\'. This is why your paths have to be wrapped in quotes, if you pass xcopy "C:\Documents and Settings" "C:\" /e then it knows the source is 'C:\Documents and Settings' the destination is 'C:\' and the arguments are '/e'.




回答2:


g = "xcopy " & h & " D:\y\ /E"



回答3:


VBscript variables are only referred to by their name, so no prefix like $ or & is required. I'd imagine the other suggestions will work



来源:https://stackoverflow.com/questions/2475319/problem-copying-files-through-xcopy-using-vbscript

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!