Powershellでファイルを解凍する方法


224

.zipファイルがあり、Powershellを使用してコンテンツ全体を解凍する必要があります。私はこれをやっていますが、うまくいかないようです:

$shell = New-Object -ComObject shell.application
$zip = $shell.NameSpace("C:\a.zip")
MkDir("C:\a")
foreach ($item in $zip.items()) {
  $shell.Namespace("C:\a").CopyHere($item)
}

どうしましたか?ディレクトリC:\aはまだ空です。


6
Powershell 2.0を使用している場合、または.NET 4.5がインストールされていない場合、言及した方法が唯一のパスです(サードパーティのexe(つまり7zip)を使用しない場合)。誰かがこの方法がうまくいかない理由を教えてくれます。私にとってはうまくいくこともあれば、うまくいかないこともあります
kenny

回答:


248

System.IO.Compression.ZipFileからExtractToDirectoryを使用する簡単な方法を次に示します。

Add-Type -AssemblyName System.IO.Compression.FileSystem
function Unzip
{
    param([string]$zipfile, [string]$outpath)

    [System.IO.Compression.ZipFile]::ExtractToDirectory($zipfile, $outpath)
}

Unzip "C:\a.zip" "C:\a"

ターゲットフォルダが存在しない場合、ExtractToDirectoryが作成することに注意してください。その他の警告:

以下も参照してください。


10
単一の関数呼び出しを置き換える関数を作成するのはなぜですか?

17
理論的にはそうではありません。関数の複雑な/型破りな呼び出しを隠そうとするので、後でそれが使用される場所を気にせずにメソッドを置き換えることができます。キースが述べたように、V5には新しい方法があります。
Micky Balladelli、2015

1
これには少なくとも.NET Framework 4.5が必要です。msdn.microsoft.com/en-us/library/

10
私はこれを試しましたが、エラーを下回っていました Exception calling "ExtractToDirectory" with "2" argument(s): "End of Central Directory record could not be found." At line:5 char:5 + [System.IO.Compression.ZipFile]::ExtractToDirectory($zipfile, $ou ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : InvalidDataException
Karthi1234

4
これにより、次のエラーが発生しますAdd-Type : Cannot add type. The assembly 'System.IO.Compression.FileSystem' could not be found.。.NET 4.6.2をインストールし、アセンブリがGACにあることを確認しましたが、このエラーが発生する理由がわかりませんでした。
Sam

500

PowerShell v5 +には、Expand-Archiveコマンド(およびCompress-Archive)が組み込まれています。

Expand-Archive c:\a.zip -DestinationPath c:\a

26
使用$PSVersionTable.PSVersionしているPowerShellのバージョンを確認するために使用します。
Brad C

1
@LoneCoder Ballmerを責めることはできないと思います。gzipが1992年にリリースされ、tarがさらに古いにもかかわらず、Windowsには、圧縮ファイルを処理するための組み込みのコマンドラインツールがありませんでした。
jpmc26 2016年

2
@Ghashange PowerShell 5は、この回答が投稿されたとき、プレリリースとしてであっても、Windows 10およびServer 2012より前のバージョンでは利用できませんでした。
jpmc26 2016年

11
パラメータOutputPathDestinationPathmsdn.microsoft.com/powershell/reference/5.1/…を参照)に変更されたように見えます
Elijah W. Gagne

1
次のような相対パスを使用することもできますExpand-Archive -Path .\a.zip -DestinationPath .
Culip

24

PowerShell v5.1では、これはv5とわずかに異なります。MSのドキュメントによると-Path、アーカイブファイルのパスを指定するパラメーターが必要です。

Expand-Archive -Path Draft.Zip -DestinationPath C:\Reference

または、これは実際のパスである可能性があります。

Expand-Archive -Path c:\Download\Draft.Zip -DestinationPath C:\Reference

Expand-Archive Doc


3
このコマンドレットでは、v5とv5.1の間に違いはありません。最初のパラメーターに名前を付ける必要はありません。自動的にパスになります。たとえば、Expand-Archive Draft.Zip -DestinationPath C:\Reference問題なく動作します。また、実際のパスではなく、絶対パスです。
フランクリンユー

13

Expand-Archiveパラメータセットの1つを指定してコマンドレットを使用します。

Expand-Archive -LiteralPath C:\source\file.Zip -DestinationPath C:\destination
Expand-Archive -Path file.Zip -DestinationPath C:\destination

12

ねえ、私のために働いています。

$shell = New-Object -ComObject shell.application
$zip = $shell.NameSpace("put ur zip file path here")
foreach ($item in $zip.items()) {
  $shell.Namespace("destination where files need to unzip").CopyHere($item)
}

2
ファイルまたはディレクトリのいずれかが宛先の場所にすでに存在する場合、目的を無効にするために何をするか(無視、上書き)を尋ねるダイアログがポップアップ表示されます。サイレント上書きを強制する方法を誰かが知っていますか?
Oleg Kazakov

@OlegKazakovによるコメントへの回答:CopyHereメソッドを制御するオプションのセットがあります。@OlegKazakovはすでに彼の問題を解決したと思います。:それでも私はこのトピックを見つけることができ、他のサーファーのために、ここでは、このリンクを置くdocs.microsoft.com/en-us/previous-versions/windows/desktop/...
jsxt

4

Shell.Application.Namespace.Folder.CopyHere()を使用し、コピー中はプログレスバーを非表示にするか、より多くのオプションを使用したい場合は、ドキュメントがこちらにあります:https :
//docs.microsoft.com/en-us / windows / desktop / shell / folder-copyhere

powershellを使用して進行状況バーを非表示にし、確認を無効にするには、次のようなコードを使用できます。

# We should create folder before using it for shell operations as it is required
New-Item -ItemType directory -Path "C:\destinationDir" -Force

$shell = New-Object -ComObject Shell.Application
$zip = $shell.Namespace("C:\archive.zip")
$items = $zip.items()
$shell.Namespace("C:\destinationDir").CopyHere($items, 1556)

WindowsコアバージョンでのShell.Applicationの使用の制限:https ://docs.microsoft.com/en-us/windows-server/administration/server-core/what-is-server-core

Windows コアバージョンでは、デフォルトでMicrosoft-Windows-Server-Shell-Packageがインストールされていないため、shell.applicatonは機能しません。

:この方法でアーカイブを抽出すると、時間がかかり、Windows GUIの速度が低下する可能性があります


3

expand-archiveアーカイブにちなんで名付けられたディレクトリを使用するが自動作成:

function unzip ($file) {
    $dirname = (Get-Item $file).Basename
    New-Item -Force -ItemType directory -Path $dirname
    expand-archive $file -OutputPath $dirname -ShowProgress
}

これは、必然的に現在のディレクトリに展開しますね。
jpmc26 2017年

自動作成の付加価値を実際に見ないでください。outputPath受け入れられた回答のように2番目のパラメーターを追加する方がより柔軟です。このソリューションでは(jpmc26が言ったように)、常に現在のディレクトリに新しいディレクトリを作成するので、呼び出す前に現在のディレクトリを設定する必要がある可能性がありますunzip
Rubanov

ほとんどのアーカイバは、アーカイブと同じ場所で、アーカイブにちなんで名付けられたディレクトリに抽出します。別のものが必要な場合にパラメーターを追加するのを止めるものはありませんが、それは賢明なデフォルトです。
mikemaccana 2017

1
function unzip {
    param (
        [string]$archiveFilePath,
        [string]$destinationPath
    )

    if ($archiveFilePath -notlike '?:\*') {
        $archiveFilePath = [System.IO.Path]::Combine($PWD, $archiveFilePath)
    }

    if ($destinationPath -notlike '?:\*') {
        $destinationPath = [System.IO.Path]::Combine($PWD, $destinationPath)
    }

    Add-Type -AssemblyName System.IO.Compression
    Add-Type -AssemblyName System.IO.Compression.FileSystem

    $archiveFile = [System.IO.File]::Open($archiveFilePath, [System.IO.FileMode]::Open)
    $archive = [System.IO.Compression.ZipArchive]::new($archiveFile)

    if (Test-Path $destinationPath) {
        foreach ($item in $archive.Entries) {
            $destinationItemPath = [System.IO.Path]::Combine($destinationPath, $item.FullName)

            if ($destinationItemPath -like '*/') {
                New-Item $destinationItemPath -Force -ItemType Directory > $null
            } else {
                New-Item $destinationItemPath -Force -ItemType File > $null

                [System.IO.Compression.ZipFileExtensions]::ExtractToFile($item, $destinationItemPath, $true)
            }
        }
    } else {
        [System.IO.Compression.ZipFileExtensions]::ExtractToDirectory($archive, $destinationPath)
    }
}

使用:

unzip 'Applications\Site.zip' 'C:\inetpub\wwwroot\Site'

最後に廃棄すること$archiveを忘れないでください$archiveFile
tom.maruska

0

ForEachループは$filepath変数内にある各ZIPファイルを処理します

    foreach($file in $filepath)
    {
        $zip = $shell.NameSpace($file.FullName)
        foreach($item in $zip.items())
        {
            $shell.Namespace($file.DirectoryName).copyhere($item)
        }
        Remove-Item $file.FullName
    }
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.