Search code examples
vbscriptwshfso

overwrite folders in visual basic script?


I'm working on a way to overwrite a folder if it already exists, with confirmation. Here is my code(along with the part I'm stuck on):

Set fso = CreateObject("Scripting.FileSystemObject")
Set shell = CreateObject("WScript.Shell")
Set network = CreateObject("WScript.Network")
username = network.userName
userprofile = shell.ExpandEnvironmentStrings("%userprofile%")

If fso.FolderExists(userprofile + "\foldername") = False Then
    fso.CreateFolder(userprofile & "\foldername")
    End If
If fso.FolderExists(userprofile + "\foldername") = True Then
    overwrite = msgbox("The directory that foldername uses(" & userprofile + "\foldername) is unavailable. Overwrite?",4+16+4096,"")
        if overwrite = vbYes then
            overwrite2 = msgbox("THIS IS YOUR LAST WARNING. Any files in " & userprofile + "\foldername will be PERMANENTLY LOST. Continue?",4+16+4096,"")
                if overwrite2 = vbYes then
                    'overwriting folder goes here
                    End If
                if overwrite2 = vbNo then
                    End If
        if overwrite = vbNo then
        End If

The "overwriting folder goes here" is where I need help. Thanks!


Solution

  • When you say overwrite folder is the intention to delete all existing content? If so could you delete the folder first and then recreate it?

    if overwrite2 = vbYes then
        strFolderPath = userprofile & "\foldername"
        fso.DeleteFolder strFolderPath, true
        fso.CreateFolder(strFolderPath)
        End If