tags:

views:

383

answers:

3

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.

A: 
g = "xcopy " & h & " D:\y\ /E"
aphoria
it is not working
sushant
what is the error you are getting?
aphoria
sushant
You can do it that way. If you look closely, I put the space inside the quote, in front of the D:.
aphoria
+1  A: 

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

Tester101
Btw, to insert quotes into a string you can use double double quotes (`""`) instead of concatenating with `Chr(34)`. Personally, I find the latter too verbose.
Helen
thanks a lot. its working now.
sushant
A: 

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

leereid