【问题标题】:Help To create Folder1/Folder2 in Windows using VBScript ( Both the folders not exists before, i mean to create multilevel folders @ a strech.)帮助使用 VBScript 在 Windows 中创建 Folder1/Folder2(这两个文件夹以前都不存在,我的意思是创建多级文件夹@a strech。)
【发布时间】:2011-05-23 09:14:36
【问题描述】:

我已经使用我的 VBscript 创建了文件夹。当我给出一个文件夹路径时,脚本只创建最后一个文件夹,如果最后一个文件夹不存在,它将失败......我需要一个 vbscript 代码来一次性创建整个文件夹结构。像 unix 中的 mkdir -p

【问题讨论】:

    标签: windows scripting vbscript


    【解决方案1】:

    你可以使用这个功能:

    Const PATH = "X:\folder0\folder1\folder2"
    
    Set fso = CreateObject("Scripting.FileSystemObject")
    
    BuildFullPath PATH
    
    Sub BuildFullPath(ByVal FullPath)
        If Not fso.FolderExists(FullPath) Then
            BuildFullPath fso.GetParentFolderName(FullPath)
            fso.CreateFolder FullPath
        End If
    End Sub
    

    或者简单地从你的脚本中调用 mkdir 命令:

    Set objShell = CreateObject("Wscript.Shell")
    objShell.Run "cmd /c mkdir X:\folder1\folder2\folder3"
    

    【讨论】:

    • 非常感谢帕斯卡的回复
    • 要使其适用于相对路径,条件可以更改为If path <> "" and not objFSO.FolderExists(path)
    • @VijayAthreyan,你不应该接受答案吗,因为它是正确的?
    • @Pascal Rodriguez,第二个选项有效,但是如果您将目录结构作为参数,您会创建一个漏洞,调用者可以在其中注入 shell 命令,不是吗?
    • 选项 2 必须与文件夹名称中的空格竞争,因此需要用引号括起来......应该这样做:Shell.Run "cmd /c mkdir """ & PATH & """"
    【解决方案2】:

    您必须拆分完整路径并创建每个文件夹。 示例函数:

    Function CreateFolderRecursive(FullPath)
      Dim arr, dir, path
      Dim oFs
    
      Set oFs = WScript.CreateObject("Scripting.FileSystemObject")
      arr = split(FullPath, "\")
      path = ""
      For Each dir In arr
        If path <> "" Then path = path & "\"
        path = path & dir
        If oFs.FolderExists(path) = False Then oFs.CreateFolder(path)
      Next
    End Function
    

    【讨论】:

    • 谢谢。这很棒。
    【解决方案3】:

    迟到了,但 Shell.Application 对象在 XP 中对我有用,如下...

    with CreateObject("Shell.Application")
      set oFolder = .NameSpace("C:\")
      if (not oFolder is nothing) then oFolder.NewFolder("a\b\c\d")
    end with
    

    【讨论】:

      【解决方案4】:

      不同意其他答案,但检查每个文件夹是否存在也是一个好主意 - 这样当您尝试创建已存在的文件夹时它不会引发错误

      Sub ensureFolderExists(strFldrPath)
          If Not FSO.FolderExists(strFldrPath) AND strFldrPath <> "" Then
              ensureFolderExists(FSO.GetParentFolderName(strFldrPath))
              FSO.CreateFolder strFldrPath
          End If
      End Sub
      

      【讨论】:

      • 只发给以后偶然发现这个话题的人
      • If Not FSO.FolderExists(FSO.GetParentFolderName(strFldrPath)) then 检查是完全多余的。只需在父级上调用ensureFolderExists,您已经进行了存在检查。您可能需要检查strFldrPath 是否为空字符串。
      • 现在看看接受的答案中的函数BuildFullPath :-))
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-27
      • 1970-01-01
      • 1970-01-01
      • 2021-02-15
      • 2022-01-21
      相关资源
      最近更新 更多