Using xcopy in VBS (With a Twist)

Casey Reynolds picture Casey Reynolds · Jul 16, 2012 · Viewed 14.8k times · Source

Okay, so here's the deal: I'm trying to put together a script that will perform a simple xcopy. The problem is I want the users to be able to browse for the source and destination folders. I've got a couple simple parts, but I've been unable to piece them together, especially trying to differentiate the source from destination, and trying to get the output from the browse function...

Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.BrowseForFolder(0, "Example", 1, "c:\Programs")

Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.BrowseForFolder(0, "Example", 1, "c:\Programs")

Set objShell = WScript.CreateObject("WScript.Shell")
objShell.Run "Xcopy ""objShell"" ""objShell"" /C /D /E /H /I /K /R /S /Y"

Any help would be greatly appreciated.

Answer

peter picture peter · Jul 16, 2012

Like this it will work, tested on Windows 7

Set objShell = CreateObject("Shell.Application")
Set oFso = CreateObject("Scripting.FileSystemObject")
root = "c:\"
Set source = get_path(objShell.BrowseForFolder(0, "Source folder", 1, root))
Set target = get_path(objShell.BrowseForFolder(0, "Target folder", 1, root))
Set objShell = WScript.CreateObject("WScript.Shell")
command = "Xcopy """&source&""" """&target&""" /C /D /E /H /I /K /R /S /Y"
'wscript.echo command
objShell.Run command

function get_path(foldername)
  Set oFolderItem = foldername.Items.Item
  Set selected = oFso.GetFolder(oFolderItem.Path)
  If selected.IsRootFolder Then
    Set get_path = oFso.GetDrive(selected.Drive)
  Else
    Set get_path = oFso.GetFolder(oFolderItem.Path)
  End If
end function