copying folder to another path getting error

2019-09-06 17:39发布

I have this below code which is copying files from one folder and creating a new folder if does not exist and then pasting the files over there.I am getting a path not found error..meaning if I want to create a new folder in c:\versions\myfolder it is not creating the path and throwing error..am I doing something wrong here.

Dim LastMonth
Dim strFolder 
Const  strFile = "C:\inetpub\wwwroot\Shared"
Const Overwrite = True
Dim oFSO

LastMonth = DateAdd("m",-1,Date)

strFolder = "C:\Versions\" & "Common_" & Replace(LastMonth,"/","-")&"/"
Set oFSO = CreateObject("Scripting.FileSystemObject")

WScript.Echo strFolder
If Not oFSO.FolderExists(strFolder) Then
  oFSO.CreateFolder strFolder
End If

oFSO.CopyFolder strFile, strFolder, Overwrite

To make the question easy to understand I also tried doing this oFSO.CreateFolder("C:\Versions\Shared") but it doe snot work.

标签: vbscript
2条回答
太酷不给撩
2楼-- · 2019-09-06 18:09
  • You can't create a folder and subfolder at the same time, the parent folder must exists before you can create the sub-folder.
  • You put a forward slash (/) in the folder name instead of a backslash (\) in the strFolder path. (Typo?!)

Hope that helps

查看更多
仙女界的扛把子
3楼-- · 2019-09-06 18:10

You can create folders including their parent folders by recursively traversing the path upwards until you find an existing parent folder, and then create the child folders as you descend back:

Set fso = CreateObject("Scripting.FileSystemObject")

Sub CreateSubFolder(path)
  If Not fso.FolderExists(path) Then
    drive = fso.GetDriveName(path)
    If Not fso.DriveExists(drive) Then
      WScript.Echo "Drive " & drive & " doesn't exist."
      WScript.Quit 1
    End If
    parent = fso.GetParentFolderName(path)
    If Not fso.FolderExists(parent) Then CreateSubFolder parent
    fso.CreateFolder path
  End If
End Sub

CreateSubFolder "C:\path\to\some\distant\sub\folder"
查看更多
登录 后发表回答