簡體   English   中英

Windows的內置ZIP壓縮可以編寫腳本嗎?

[英]Can Windows' built-in ZIP compression be scripted?

Windows XP / Vista / 2003/2008中內置的ZIP壓縮是否能夠編寫腳本? 我必須從BAT / CMD文件中調用哪些可執行文件? 或者是否可以使用VBScript執行此操作?

我意識到這可以使用WinZip7-Zip和其他外部應用程序,但我正在尋找一些不需要安裝外部應用程序的東西。

有VBA的方法來壓縮解壓使用內置的壓縮以及窗戶,這應該給一些有識之士為系統如何運作的。 您可以將這些方法構建為您選擇的腳本語言。

基本原則是在Windows中,您可以將zip文件視為目錄,並將其復制到其中。 因此,要創建一個新的zip文件,只需創建一個擴展名為.zip的文件,該文件具有用於空zip文件的正確標頭。 然后你關閉它,並告訴Windows你想要將文件復制到它,就好像它是另一個目錄。

解壓縮更容易 - 只需將其視為目錄即可。

如果網頁再次丟失,以下是一些相關的代碼片段:

壓縮

Sub NewZip(sPath)
'Create empty Zip File
'Changed by keepITcool Dec-12-2005
    If Len(Dir(sPath)) > 0 Then Kill sPath
    Open sPath For Output As #1
    Print #1, Chr$(80) & Chr$(75) & Chr$(5) & Chr$(6) & String(18, 0)
    Close #1
End Sub


Function bIsBookOpen(ByRef szBookName As String) As Boolean
' Rob Bovey
    On Error Resume Next
    bIsBookOpen = Not (Application.Workbooks(szBookName) Is Nothing)
End Function


Function Split97(sStr As Variant, sdelim As String) As Variant
'Tom Ogilvy
    Split97 = Evaluate("{""" & _
                       Application.Substitute(sStr, sdelim, """,""") & """}")
End Function

Sub Zip_File_Or_Files()
    Dim strDate As String, DefPath As String, sFName As String
    Dim oApp As Object, iCtr As Long, I As Integer
    Dim FName, vArr, FileNameZip

    DefPath = Application.DefaultFilePath
    If Right(DefPath, 1) <> "\" Then
        DefPath = DefPath & "\"
    End If

    strDate = Format(Now, " dd-mmm-yy h-mm-ss")
    FileNameZip = DefPath & "MyFilesZip " & strDate & ".zip"

    'Browse to the file(s), use the Ctrl key to select more files
    FName = Application.GetOpenFilename(filefilter:="Excel Files (*.xl*), *.xl*", _
                    MultiSelect:=True, Title:="Select the files you want to zip")
    If IsArray(FName) = False Then
        'do nothing
    Else
        'Create empty Zip File
        NewZip (FileNameZip)
        Set oApp = CreateObject("Shell.Application")
        I = 0
        For iCtr = LBound(FName) To UBound(FName)
            vArr = Split97(FName(iCtr), "\")
            sFName = vArr(UBound(vArr))
            If bIsBookOpen(sFName) Then
                MsgBox "You can't zip a file that is open!" & vbLf & _
                       "Please close it and try again: " & FName(iCtr)
            Else
                'Copy the file to the compressed folder
                I = I + 1
                oApp.Namespace(FileNameZip).CopyHere FName(iCtr)

                'Keep script waiting until Compressing is done
                On Error Resume Next
                Do Until oApp.Namespace(FileNameZip).items.Count = I
                    Application.Wait (Now + TimeValue("0:00:01"))
                Loop
                On Error GoTo 0
            End If
        Next iCtr

        MsgBox "You find the zipfile here: " & FileNameZip
    End If
End Sub

UNZIP

Sub Unzip1()
    Dim FSO As Object
    Dim oApp As Object
    Dim Fname As Variant
    Dim FileNameFolder As Variant
    Dim DefPath As String
    Dim strDate As String

    Fname = Application.GetOpenFilename(filefilter:="Zip Files (*.zip), *.zip", _
                                        MultiSelect:=False)
    If Fname = False Then
        'Do nothing
    Else
        'Root folder for the new folder.
        'You can also use DefPath = "C:\Users\Ron\test\"
        DefPath = Application.DefaultFilePath
        If Right(DefPath, 1) <> "\" Then
            DefPath = DefPath & "\"
        End If

        'Create the folder name
        strDate = Format(Now, " dd-mm-yy h-mm-ss")
        FileNameFolder = DefPath & "MyUnzipFolder " & strDate & "\"

        'Make the normal folder in DefPath
        MkDir FileNameFolder

        'Extract the files into the newly created folder
        Set oApp = CreateObject("Shell.Application")

        oApp.Namespace(FileNameFolder).CopyHere oApp.Namespace(Fname).items

        'If you want to extract only one file you can use this:
        'oApp.Namespace(FileNameFolder).CopyHere _
         'oApp.Namespace(Fname).items.Item("test.txt")

        MsgBox "You find the files here: " & FileNameFolder

        On Error Resume Next
        Set FSO = CreateObject("scripting.filesystemobject")
        FSO.deletefolder Environ("Temp") & "\Temporary Directory*", True
    End If
End Sub

是的,這可以使用VBScript編寫腳本。 例如,以下代碼可以從目錄創建zip:

Dim fso, winShell, MyTarget, MySource, file
Set fso = CreateObject("Scripting.FileSystemObject")
Set winShell = createObject("shell.application")


MyTarget = Wscript.Arguments.Item(0)
MySource = Wscript.Arguments.Item(1)

Wscript.Echo "Adding " & MySource & " to " & MyTarget

'create a new clean zip archive
Set file = fso.CreateTextFile(MyTarget, True)
file.write("PK" & chr(5) & chr(6) & string(18,chr(0)))
file.close

winShell.NameSpace(MyTarget).CopyHere winShell.NameSpace(MySource).Items

do until winShell.namespace(MyTarget).items.count = winShell.namespace(MySource).items.count
    wscript.sleep 1000 
loop

Set winShell = Nothing
Set fso = Nothing

您還可以找到http://www.naterice.com/blog/template_permalink.asp?id=64,因為它包含VBScript中的完整Unzip / Zip實現。

如果每500毫秒進行一次大小檢查而不是項目計數,則對大文件更有效。 盡管Win 7沒有完成壓縮,Win 7會立即寫入文件:

set fso=createobject("scripting.filesystemobject")
Set h=fso.getFile(DestZip)
do
    wscript.sleep 500
    max = h.size
loop while h.size > max 

適用於大量日志文件。

為了清楚起見:GZip不是像Guy Starbuck在8月的評論中所建議的僅MS算法。 System.IO.Compression中的GZipStream使用Deflate算法,與zlib庫和許多其他zip工具相同。 該類可與gix等unix實用程序完全互操作。

GZipStream類不能從命令行或VBScript編寫腳本,以生成ZIP文件,因此它不能解決原始海報的請求。

免費的DotNetZip庫可以讀取和生成zip文件,可以從VBScript或Powershell編寫腳本。 它還包括用於生成和讀取/提取zip文件的命令行工具。

這是VBScript的一些代碼:

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

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

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

WScript.echo("setting the password...")
zip.Password = "Very.Secret.Password!"

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

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

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

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

WScript.echo("Done.")

以下是Powershell的一些代碼:

[System.Reflection.Assembly]::LoadFrom("c:\\dinoch\\bin\\Ionic.Zip.dll");

$directoryToZip = "c:\\temp";
$zipfile =  new-object Ionic.Zip.ZipFile;
$e= $zipfile.AddEntry("Readme.txt", "This is a zipfile created from within powershell.")
$e= $zipfile.AddDirectory($directoryToZip, "home")
$zipfile.Save("ZipFiles.ps1.out.zip");

在.bat或.cmd文件中,您可以使用zipit.exe或unzip.exe工具。 例如:

zipit NewZip.zip  -s "This is string content for an entry"  Readme.txt  src 

這是我嘗試總結壓縮和解壓縮的內置功能窗口 - 如何在不使用任何外部工具的情況下使用批處理文件壓縮(/ zip)和解壓縮(/解壓縮)文件和文件夾?

一些給定的解決方案應該適用於幾乎所有的Windows機器。

關於shell.application和WSH,我更喜歡jscript,因為它允許混合批處理/ jscript文件(擴展名為.bat),不需要臨時文件。我已將unzip和zip功能放在一個文件中,還有一些其他功能。

要創建壓縮存檔,您可以使用實用程序MAKECAB.EXE

在SourceForge( http://sourceforge.net/projects/unxutils )上提供的UnxUtils包中有zip和unzip可執行文件(以及其他有用應用程序的船載)。 將它們復制到PATH中的某個位置,例如“c:\\ windows”,您就可以將它們包含在腳本中。

這不是一個完美的解決方案(或者你要求的那個),而是一個體面的工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM