명령 줄에서 .zip 폴더 만들기-(Windows)


57

명령 줄의 폴더에서 .zip 파일을 만들 수 있습니까? 타사 실행 파일을 사용하고 싶지 않습니다.

'압축 폴더로 보내기'와 같은 것을 생각하고 있었지만 어떻게 해야할지 모르겠습니다 ...


2
Windows 리소스 키트에는이라는 도구가 있습니다 compress.exe.
— ho1

2
다음은 이것에 대해서만 설명하는 ServerFault 질문에 대한 링크입니다. serverfault.com/questions/39071/…
— ho1

답변:



7

Windows에 내장 된 ZIP 파일에 대한 명령 줄이 없다고 생각합니다 ( compressServer 2003 Resource Kit 제외). 타사를 사용해야합니다. 모두 7zip을 좋아합니다 !


6

이 스크립트를 여러 가지 소스에서 결합하여 내 요구에 더 잘 맞았습니다. 스크립트를 복사하여 확장자가 ".vbs"인 파일에 붙여 넣습니다. 이 스크립트는 원래 Windows XP 용으로 만들어졌지만 Windows 7 x64 Ultimate에서도 작동합니다. Windows에서 사용하는 다양한 셸 개체를 유지할지 여부는 보장 할 수 없습니다.

사용법 : 실행 상자 또는 명령 줄에서

"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

나는 같은 문제를 가지고있다. 위의 코드가 작동하지 않거나 포스터에서 언급하지 않은 시스템에 추가 항목이 필요합니다.
— Shaamaan '

WScript (vbs 환경)와 여러 Shell 개체를 사용합니다. 모두 기본적으로 Windows XP (business?) 및 Win 7 Ultimate x64에 설치되었습니다. 아마도 그들은 Win8을 위해 더 오래 있습니까?
— WSkid

2

BAT에서 PowerShell 스크립트를 실행할 수 있습니다. Bat 파일은 압축 될 dir의 경로와 매개 변수로 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를 사용하는데, 이는 반드시 Windows 고유의 것은 아니지만 너무 일반적이기 때문에 일반적입니다.

Windows 7은 기본적으로 설치된 명령 줄에서 압축 해제되어 있습니까?

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


3
답에 지시 사항을 포함시켜야합니다. 링크가 오래되면 응답이 쓸모가 없습니다.
— MoonSire

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 파일이 항목 컬렉션에 포함되므로 타이밍 문제입니다.

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

당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.