使用 VBScript 从 ZIP 文件中提取文件

发布于 2024-07-09 03:26:37 字数 905 浏览 10 评论 0原文

从 ZIP 文件中提取文件时,我使用了以下命令。

Sub Unzip(strFile)
' This routine unzips a file. NOTE: The files are extracted to a folder '
' in the same location using the name of the file minus the extension.  '
' EX. C:\Test.zip will be extracted to C:\Test '
'strFile (String) = Full path and filename of the file to be unzipped. '
Dim arrFile
    arrFile = Split(strFile, ".")
    Set fso = CreateObject("Scripting.FileSystemObject")
    fso.CreateFolder(arrFile(0) & "\ ")
    pathToZipFile= arrFile(0) & ".zip"
    extractTo= arrFile(0) & "\ "
    set objShell = CreateObject("Shell.Application")
    set filesInzip=objShell.NameSpace(pathToZipFile).items
    objShell.NameSpace(extractTo).CopyHere(filesInzip)
    fso.DeleteFile pathToZipFile, True
    Set fso = Nothing
    Set objShell = Nothing
End Sub 'Unzip

这是有效的,但现在我收到“文件存在”错误。

这是什么原因呢? 还有其他选择吗?

When extracting files from a ZIP file I was using the following.

Sub Unzip(strFile)
' This routine unzips a file. NOTE: The files are extracted to a folder '
' in the same location using the name of the file minus the extension.  '
' EX. C:\Test.zip will be extracted to C:\Test '
'strFile (String) = Full path and filename of the file to be unzipped. '
Dim arrFile
    arrFile = Split(strFile, ".")
    Set fso = CreateObject("Scripting.FileSystemObject")
    fso.CreateFolder(arrFile(0) & "\ ")
    pathToZipFile= arrFile(0) & ".zip"
    extractTo= arrFile(0) & "\ "
    set objShell = CreateObject("Shell.Application")
    set filesInzip=objShell.NameSpace(pathToZipFile).items
    objShell.NameSpace(extractTo).CopyHere(filesInzip)
    fso.DeleteFile pathToZipFile, True
    Set fso = Nothing
    Set objShell = Nothing
End Sub 'Unzip

This was working, but now I get a "The File Exists" Error.

What is the reason for this? Are there any alternatives?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

后eg是否自 2024-07-16 03:26:37

上述所有解决方案都是准确的,但它们不是确定的。

如果您尝试将压缩文件解压到临时文件夹中,将立即创建一个显示“Temporary Folder For YOURFILE.zip”的文件夹(位于C:\DocumentsSettings\USERNAME\Local Settings\Temp),用于您尝试提取的 ZIP 文件中包含的每个文件

没错,如果您有 50 个文件,它将在您的临时目录中创建 50 个文件夹。

但是如果您有 200 个文件,它将停止在 99 个文件并崩溃并提示 - 文件存在

..

显然,根据我在上面查看的贡献,这种情况不会发生在 Windows 7 上。 但无论如何,我们仍然可以进行检查。 好吧,这就是修复它的方法:

    '========================
    'Sub: UnzipFiles
    'Language: vbscript
    'Usage: UnzipFiles("C:\dir", "extract.zip")
    'Definition: UnzipFiles([Directory where zip is located & where files will be extracted], [zip file name])
    '========================
    Sub UnzipFiles(folder, file)
        Dim sa, filesInzip, zfile, fso, i : i = 1
        Set sa = CreateObject("Shell.Application")
            Set filesInzip=sa.NameSpace(folder&file).items
        For Each zfile In filesInzip
            If Not fso.FileExists(folder & zfile) Then
                sa.NameSpace(folder).CopyHere(zfile), &H100 
                i = i + 1
            End If
            If i = 99 Then
            zCleanup(file, i)
            i = 1
            End If
        Next
        If i > 1 Then 
            zCleanup(file, i)
        End If
        fso.DeleteFile(folder&file)
    End Sub

    '========================
    'Sub: zCleanup
    'Language: vbscript
    'Usage: zCleanup("filename.zip", 4)
    'Definition: zCleanup([Filename of Zip previously extracted], [Number of files within zip container])
    '========================
    Sub zCleanUp(file, count)   
        'Clean up
        Dim i, fso
        Set fso = CreateObject("Scripting.FileSystemObject")
        For i = 1 To count
           If fso.FolderExists(fso.GetSpecialFolder(2) & "\Temporary Directory " & i & " for " & file) = True Then
           text = fso.DeleteFolder(fso.GetSpecialFolder(2) & "\Temporary Directory " & i & " for " & file, True)
           Else
              Exit For
           End If
        Next
    End Sub

就是这样,将这两个函数复制并粘贴到您的 VBScript 托管程序中,您应该可以在 Windows XP 和 Windows 上开始使用了。 Windows 7。

谢谢!

All above solutions are accurate, but they are not definitive.

If you are trying to extract a zipped file into a temporary folder, a folder that displays "Temporary Folder For YOURFILE.zip" will immediately be created (in C:\Documents and Settings\USERNAME\Local Settings\Temp) for EACH FILE contained within your ZIP file, which you are trying to extract.

That's right, if you have 50 files, it will create 50 folders within your temp directory.

But if you have 200 files, it will stop at 99 and crash stating - The File Exists.

..

Apparently, this does not occur on Windows 7 with the contributions I view above. But regardless, we can still have checks. Alright, so this is how you fix it:

    '========================
    'Sub: UnzipFiles
    'Language: vbscript
    'Usage: UnzipFiles("C:\dir", "extract.zip")
    'Definition: UnzipFiles([Directory where zip is located & where files will be extracted], [zip file name])
    '========================
    Sub UnzipFiles(folder, file)
        Dim sa, filesInzip, zfile, fso, i : i = 1
        Set sa = CreateObject("Shell.Application")
            Set filesInzip=sa.NameSpace(folder&file).items
        For Each zfile In filesInzip
            If Not fso.FileExists(folder & zfile) Then
                sa.NameSpace(folder).CopyHere(zfile), &H100 
                i = i + 1
            End If
            If i = 99 Then
            zCleanup(file, i)
            i = 1
            End If
        Next
        If i > 1 Then 
            zCleanup(file, i)
        End If
        fso.DeleteFile(folder&file)
    End Sub

    '========================
    'Sub: zCleanup
    'Language: vbscript
    'Usage: zCleanup("filename.zip", 4)
    'Definition: zCleanup([Filename of Zip previously extracted], [Number of files within zip container])
    '========================
    Sub zCleanUp(file, count)   
        'Clean up
        Dim i, fso
        Set fso = CreateObject("Scripting.FileSystemObject")
        For i = 1 To count
           If fso.FolderExists(fso.GetSpecialFolder(2) & "\Temporary Directory " & i & " for " & file) = True Then
           text = fso.DeleteFolder(fso.GetSpecialFolder(2) & "\Temporary Directory " & i & " for " & file, True)
           Else
              Exit For
           End If
        Next
    End Sub

And that's it, copy and paste those two functions into your VBScript hosted program and you should be good to go, on Windows XP & Windows 7.

Thanks!

薄荷梦 2024-07-16 03:26:37

您可以从 VBScript 使用 DotNetZip

要解压现有的 zip 文件,覆盖可能存在的任何文件:

WScript.echo("Instantiating a ZipFile object...")
Dim zip 
Set zip = CreateObject("Ionic.Zip.ZipFile")

WScript.echo("Initialize (Read)...")
zip.Initialize("C:\Temp\ZipFile-created-from-VBScript.zip")

WScript.echo("setting the password for extraction...")
zip.Password = "This is the Password."

' set the default action for extracting an existing file
' 0 = throw exception
' 1 = overwrite silently
' 2 = don't overwrite (silently)
' 3 = invoke the ExtractProgress event
zip.ExtractExistingFile = 1

WScript.echo("extracting all files...")
Call zip.ExtractAll("extract")

WScript.echo("Disposing...")
zip.Dispose()

WScript.echo("Done.")

要创建新的 zip 文件:

dim filename 
filename = "C:\temp\ZipFile-created-from-VBScript.zip"

WScript.echo("Instantiating a ZipFile object...")
dim zip2 
set zip2 = CreateObject("Ionic.Zip.ZipFile")

WScript.echo("using AES256 encryption...")
zip2.Encryption = 3

WScript.echo("setting the password...")
zip2.Password = "This is the Password."

WScript.echo("adding a selection of files...")
zip2.AddSelectedFiles("*.js")
zip2.AddSelectedFiles("*.vbs")

WScript.echo("setting the save name...")
zip2.Name = filename

WScript.echo("Saving...")
zip2.Save()

WScript.echo("Disposing...")
zip2.Dispose()

WScript.echo("Done.")

You can use DotNetZip from VBScript.

To unpack an existing zipfile, overwriting any files that may exist:

WScript.echo("Instantiating a ZipFile object...")
Dim zip 
Set zip = CreateObject("Ionic.Zip.ZipFile")

WScript.echo("Initialize (Read)...")
zip.Initialize("C:\Temp\ZipFile-created-from-VBScript.zip")

WScript.echo("setting the password for extraction...")
zip.Password = "This is the Password."

' set the default action for extracting an existing file
' 0 = throw exception
' 1 = overwrite silently
' 2 = don't overwrite (silently)
' 3 = invoke the ExtractProgress event
zip.ExtractExistingFile = 1

WScript.echo("extracting all files...")
Call zip.ExtractAll("extract")

WScript.echo("Disposing...")
zip.Dispose()

WScript.echo("Done.")

To create a new zipfile:

dim filename 
filename = "C:\temp\ZipFile-created-from-VBScript.zip"

WScript.echo("Instantiating a ZipFile object...")
dim zip2 
set zip2 = CreateObject("Ionic.Zip.ZipFile")

WScript.echo("using AES256 encryption...")
zip2.Encryption = 3

WScript.echo("setting the password...")
zip2.Password = "This is the Password."

WScript.echo("adding a selection of files...")
zip2.AddSelectedFiles("*.js")
zip2.AddSelectedFiles("*.vbs")

WScript.echo("setting the save name...")
zip2.Name = filename

WScript.echo("Saving...")
zip2.Save()

WScript.echo("Disposing...")
zip2.Dispose()

WScript.echo("Done.")
星軌x 2024-07-16 03:26:37

上面的答案是完全正确的,但我想我应该将所有内容都包含到我正在使用的完整解决方案中:

strZipFile = "test.zip"     'name of zip file
outFolder = "."             'destination folder of unzipped files (must exist)
'If using full paths rather than relative to the script, comment the next line
pwd = Replace(WScript.ScriptFullName, WScript.ScriptName, "")

Set objShell = CreateObject( "Shell.Application" )
Set objSource = objShell.NameSpace(pwd+strZipFile).Items()
Set objTarget = objShell.NameSpace(pwd+outFolder)
intOptions = 256
objTarget.CopyHere objSource, intOptions

'Clean up
Set WshShell = CreateObject("Wscript.Shell")
tempfolder = WshShell.ExpandEnvironmentStrings("%temp%")
Set fso = CreateObject("Scripting.FileSystemObject")
Call fso.DeleteFolder(tempfolder + "\Temporary Directory 1 for " + strZipFile, True )  

There's answers above which are perfectly correct, but I thought I'd wrap everything up into a full solution that I'm using:

strZipFile = "test.zip"     'name of zip file
outFolder = "."             'destination folder of unzipped files (must exist)
'If using full paths rather than relative to the script, comment the next line
pwd = Replace(WScript.ScriptFullName, WScript.ScriptName, "")

Set objShell = CreateObject( "Shell.Application" )
Set objSource = objShell.NameSpace(pwd+strZipFile).Items()
Set objTarget = objShell.NameSpace(pwd+outFolder)
intOptions = 256
objTarget.CopyHere objSource, intOptions

'Clean up
Set WshShell = CreateObject("Wscript.Shell")
tempfolder = WshShell.ExpandEnvironmentStrings("%temp%")
Set fso = CreateObject("Scripting.FileSystemObject")
Call fso.DeleteFolder(tempfolder + "\Temporary Directory 1 for " + strZipFile, True )  
若能看破又如何 2024-07-16 03:26:37

http://www.experts-exchange.com/Programming/ Languages/Visual_Basic/VB_Script/Q_23022290.html

检查您的临时目录。 如果您有 99 个与此解压缩过程关联的文件夹,请尝试删除它们。

http://www.experts-exchange.com/Programming/Languages/Visual_Basic/VB_Script/Q_23022290.html

Check your temp directory. If you have 99 folders associated with this unzipping process, try deleting them.

水染的天色ゝ 2024-07-16 03:26:37

我将以下代码添加到解压缩过程的开头,以在解压缩之前删除这些目录:

For i = 1 To 99
  If aqFileSystem.Exists(GetAppPath("Local Settings", "") & "\Temp\Temporary Directory " & i & " for DialogState.zip") = True Then
      result = aqFileSystem.ChangeAttributes(GetAppPath("Local Settings", "") & "\Temp\Temporary Directory " & i & " for DialogState.zip", 1 OR 2, aqFileSystem.fattrFree) 
      Call DelFolder(GetAppPath("Local Settings", "") & "\Temp\Temporary Directory " & i & " for DialogState.zip")  
   Else
      Exit For
   End If
Next

I added the following code to the beginning of my unzip procedure to delete these directories before I unzip:

For i = 1 To 99
  If aqFileSystem.Exists(GetAppPath("Local Settings", "") & "\Temp\Temporary Directory " & i & " for DialogState.zip") = True Then
      result = aqFileSystem.ChangeAttributes(GetAppPath("Local Settings", "") & "\Temp\Temporary Directory " & i & " for DialogState.zip", 1 OR 2, aqFileSystem.fattrFree) 
      Call DelFolder(GetAppPath("Local Settings", "") & "\Temp\Temporary Directory " & i & " for DialogState.zip")  
   Else
      Exit For
   End If
Next
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文