从命令行创建.zip文件夹-(Windows)


57

是否可以从命令行中的文件夹创建.zip文件,我不想使用任何第三方可执行文件。

我在想类似“发送到压缩文件夹”之类的东西,但我不知道该怎么做...


2
Windows资源工具包中有一个名为的工具compress.exe
2010年

2
这是一个ServerFault问题的链接,该问题仅讨论以下内容:serverfault.com/questions/39071/…– 2010
1

Answers:



7

我不认为Windows内置的ZIP文件没有命令行(compressServer 2003 Resource Kit中除外)。您必须使用第三方。每个人都喜欢7zip


6

我从多个不同来源组合了此脚本,以更好地满足我的需求。将脚本复制并粘贴到扩展名为“ .vbs”的文件中。该脚本最初是为Windows XP创建的,但它也可以在Windows 7 x64 Ultimate中使用-不能保证Windows是否会保留使用的各种Shell对象。

用法:在运行框或命令行中输入-

"C:\zipper.vbs" "C:\folderToZip\" "C:\mynewzip.zip"

脚本路径,源文件夹,要创建的zip文件(末尾包括.zip)。

它不会复制空文件夹,所以要小心。

这是vbs代码-

Set Args = Wscript.Arguments
source = Args(0)
target = Args(1)

' make sure source folder has \ at end
If Right(source, 1) <> "\" Then
    source = source & "\"
End If

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set zip = objFSO.OpenTextFile(target, 2, vbtrue)
' this is the header to designate a file as a zip
zip.Write "PK" & Chr(5) & Chr(6) & String( 18, Chr(0) )
zip.Close
Set zip = nothing

wscript.sleep 500

Set objApp = CreateObject( "Shell.Application" )
intSkipped = 0

' Loop over items within folder and use CopyHere to put them into the zip folder
For Each objItem in objApp.NameSpace( source ).Items
    If objItem.IsFolder Then
        Set objFolder = objFSO.GetFolder( objItem.Path )
        ' if this folder is empty, then skip it as it can't compress empty folders
        If objFolder.Files.Count + objFolder.SubFolders.Count = 0 Then
            intSkipped = intSkipped + 1
        Else
            objApp.NameSpace( target ).CopyHere objItem
        End If
    Else
        objApp.NameSpace( target ).CopyHere objItem
    End If
Next

intSrcItems = objApp.NameSpace( source ).Items.Count
wscript.sleep 250

' delay until at least items at the top level are available
Do Until objApp.NameSpace( target ).Items.Count + intSkipped = intSrcItems
    wscript.sleep 200
Loop

'cleanup
Set objItem = nothing
Set objFolder = nothing
Set objApp = nothing
Set objFSO = nothing

1
看起来很有希望,但是在第16行出现了“需要对象:'objApp.NameSpace(...)'错误
pihentagy,2012年

我也有同样的问题。上面的代码不起作用,或者在发布者忘记提及的系统中需要一些额外的东西。
Shaamaan

它使用WScript(vbs环境)和几个Shell对象。默认情况下,所有这些都已安装在Windows XP(企业版)和Win 7 Ultimate x64中。也许它们对于Win8更长一些?
WSkid

2

可以从BAT运行PowerShell脚本。Bat文件接收要压缩目录的路径和zip文件名作为参数。

@echo off
setlocal

rem First parameter - path to dir to be zipped
rem Second parameter- zip file name
set sourceDir=%1
set zipFile=%2

rem Create PowerShell script
echo Write-Output 'Custom PowerShell profile in effect!'    > %~dp0TempZipScript.ps1
echo Add-Type -A System.IO.Compression.FileSystem           >> %~dp0TempZipScript.ps1
echo [IO.Compression.ZipFile]::CreateFromDirectory('%sourceDir%','%~dp0%zipFile%') >> %~dp0TempZipScript.ps1

rem Execute script with flag "-ExecutionPolicy Bypass" to get around ExecutionPolicy
PowerShell.exe -ExecutionPolicy Bypass -Command "& '%~dp0TempZipScript.ps1'"
del %~dp0TempZipScript.ps1
endlocal

1
但是这种方法的好处是什么?为什么不只将PowerShell脚本写入固定文件并让其接受参数?
赛斯

我尝试了所有其他解决方案。这是唯一完美运行的故障安全解决方案。最重要的优点是使用powershell的本机命令,而无需创建老式的VBScript。
desmati

这为我在2019
。– simbo1905

1

这是一个很棒的链接,显示了如何使用Windows本机命令压缩文件。

您能否仅使用Windows的内置功能从命令提示符中压缩文件?

我用一个包含多个嵌套文件和文件夹的目录对其进行了测试,它运行良好。只需遵循命令行格式即可。

我也找到了一种通过命令行解压缩文件的方法。一种方法是,打开浏览器窗口,显示压缩文件的内容。其中一些还使用Java,而Java不一定是Windows固有的,而是非常普遍,以至于看起来几乎是这样。

Windows 7是否默认在安装的命令行上解压缩?

https://stackoverflow.com/questions/1021557/how-to-unzip-a-file-using-the-command-line


3
您应该在回答中包含说明。如果链接过时,您的答案将毫无价值……
MoonSire 2013年

1

这是一个老问题,但它的相关性仍然是当前的。

Windows当然具有内置的压缩​​算法以使用zip文件,但是与在http://www.7-zip.org/上找到的7zip开源产品相比,它的性能确实很差

其他人已经讨论了使用内置Windows功能的各种方法,我的解决方案需要安装其他软件。

7Zip支持多种文件,包括ZIP,RAR,CAB和ISO,并且它是自己的7z格式。

您可以查看命令行帮助:“ C:\ Program Files \ 7-Zip \ 7z.exe” --help

执行一个简单的添加到zip存档:

“ C:\ Program Files \ 7-Zip \ 7z.exe”文件名.zip c:\ path


1

这是来自4个不同来源的另一个想法。不是我的想法,但我整理了它们以使其对​​我有用

<!-- : Begin batch script
@each off

set sourceFolder="c:\test"
set destZip="%userprofile%\desktop\example.zip"

cscript //nologo "%~f0?.wsf" //job:exewsh %sourceFolder% %destZip%

exit /b
GOTO:EOF
----- Begin wsf script --->
<package><job id="exewsh"><script language="VBScript">
'Get command-line arguments.
Set objArgs = WScript.Arguments
InputFolder = objArgs(0)
ZipFile = objArgs(1)

'Create empty ZIP file.
CreateObject("Scripting.FileSystemObject").CreateTextFile(ZipFile, True).Write "PK" & Chr(5) & Chr(6) & String(18, vbNullChar)

Set objShell = CreateObject("Shell.Application")
Set source = objShell.NameSpace(InputFolder).Items
objShell.NameSpace(ZipFile).CopyHere(source)

'Required!
wScript.Sleep 2000
</script></job>
</package>

2
欢迎来到超级用户!这显然是一个复杂的脚本。您能解释一下它的作用以及如何使用吗?
jpaugh

1

假设您要压缩命令提示符下的相同文件夹,而无需打开Powershell窗口:

powershell Compress-Archive . publish.zip

那不是我打算要做的,但是现在它对我有用。这是一个方便的窍门。
bballdave025

0

我将发布与WSkids答案有关的内容,因为我无法使用注释功能。

在VBS中使用CopyHere()方法会引入一些问题。这些问题之一是,当复制过程在后台启动时,该方法立即返回,而多个CopyHere()调用将相互干扰,并且将无法正确创建ZIP。这里需要一个等待循环来解决该问题。我的等待循环基于此处发布的类似问题的答案。

这是一个更新的版本,修复了pihentagy报告的“需要对象”错误。这是一个时间问题,因为在快速计算机上执行脚本时,新创建的ZIP文件包含在Items集合中。

set Args = WScript.Arguments
source = Args(0)
' remove trailing slashes as we add slashes when needed later
while Right(source, 1) = "\"
    source = Mid(source, 1, Len(source) - 1)
wend

target = Args(1)

' create empty ZIP file
set fso = CreateObject("Scripting.FileSystemObject")
set zip = fso.OpenTextFile(target, 2, vbtrue)
' write ZIP header, this ensures that Windows recognizes the file as "ZIP Folder"
zip.Write "PK" & Chr(5) & Chr(6) & String(18, Chr(0))
zip.Close
set zip = nothing
set fso = nothing

' copy files to ZIP file
set app = CreateObject("Shell.Application")

set sourceFolderObj = app.NameSpace(source)
set targetFolderObj = app.NameSpace(target)

for each item in sourceFolderObj.Items
  itemPath = source & "\" & item.Name

  copyItem = false

  ' ZIP file is included in Items collection and is recognized as folder, thus skip it to avoid script errors
  if itemPath <> target then
    if item.IsFolder then
      if item.GetFolder.Items().Count = 0 then
        ' folder is empty, skip it as empty folders can't be compressed
      else
        copyItem = true
      end if
    else
      copyItem = true
    end if
  end if

  if copyItem then
    targetFolderObj.CopyHere item

    ' wait until the file appears in the ZIP file, 
    ' this is needed because CopyHere() returns immediately after starting an asynchronous copy process 
    ' (starting multiple asynchronous copy will not work as it causes error messages, an invalid ZIP file, ...)
    while (targetFolderObj.ParseName(item.Name) is nothing)
      WScript.Sleep 1
    wend
  end If
next

set targetFolderObj = nothing
set sourceFolderObj = nothing
set app = nothing

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.