Extract files from ZIP file with VBScript

2019-01-17 23:00发布

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?

标签: vbscript zip
5条回答
小情绪 Triste *
2楼-- · 2019-01-17 23:32

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!

查看更多
疯言疯语
3楼-- · 2019-01-17 23:36

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.")
查看更多
Anthone
4楼-- · 2019-01-17 23:36

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.

查看更多
兄弟一词,经得起流年.
5楼-- · 2019-01-17 23:48

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
查看更多
▲ chillily
6楼-- · 2019-01-17 23:49

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 )  
查看更多
登录 后发表回答