Question

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.

Was it helpful?

Solution

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'.

OTHER TIPS

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

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top