ChatGPT解决这个技术问题 Extra ChatGPT

如何在 Powershell 中解压缩文件?

我有一个 .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 仍为空。

如果您使用的是 Powershell 2.0,或者没有安装 .NET 4.5,那么您提到的方法是唯一的途径(不使用 3rd-party exe(即 7zip)。我会说这个问题直到有人提供了为什么这种方法不起作用。它在某些时候对我有用,但在其他时候却没有。
由于 Expand-Archive 现在存在于 powershell 中,因此接受的答案有点过时了。

L
Lam Le

在 PowerShell v5+ 中,内置了一个 Expand-Archive command(以及 Compress-Archive):

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

使用 $PSVersionTable.PSVersion 确定您正在运行的 PowerShell 版本。
@Ghashange PowerShell 5 在发布此答案时甚至不适用于 Windows 10 和 Server 2012 以下的任何版本,即使作为预发布版本也是如此。
看起来参数 OutputPath 已更改为 DestinationPath(参考 msdn.microsoft.com/powershell/reference/5.1/…
您还可以使用 Expand-Archive -Path .\a.zip -DestinationPath . 等相对路径
请注意,Expand-ArchiveCompress-Archive 要求存档文件扩展名为 .zip,而基于 [System.IO.Compression.ZipFile] 的解决方案则不需要。
L
Lekensteyn

以下是使用 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 将创建它。其他注意事项:

现有文件不会被覆盖,而是会触发 IOException。

此方法至少需要 .NET Framework 4.5,适用于 Windows Vista 和更高版本。

不根据当前工作目录解析相对路径,请参阅为什么 PowerShell 中的 .NET 对象不使用当前目录?

也可以看看:

如何压缩和提取文件 (Microsoft Docs)


除非路径中有空格,否则无需引用参数 C:\a.zip 或 C:\a。 PowerShell 将参数视为字符串或数字类型,除非参数以 $、@、( 或 { 等特殊字符开头。这是 PowerShell 作为 shell 脚本语言的好处之一。:-)
为什么要创建一个函数来替换单个函数调用?
理论上你不会。我尝试在函数中隐藏复杂/非常规的调用,以便稍后我可以替换该方法而不必担心它的使用位置。正如 Keith 所提到的,在 V5 中将会有一种新的方式来做到这一点。
我试过这个但得到以下错误,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
这给了我以下错误:Add-Type : Cannot add type. The assembly 'System.IO.Compression.FileSystem' could not be found.。我已经安装了 .NET 4.6.2,并且我已经验证了该程序集在 GAC 中,但我不知道为什么会出现这个错误。
I
Igor Popov

在 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


此 Cmdlet 中的 v5 和 v5.1 没有区别。您不需要命名第一个参数;它会自动成为路径。例如,Expand-Archive Draft.Zip -DestinationPath C:\Reference 可以正常工作。另外,它不是实际路径,而是绝对路径。
S
Saleh Rahimzadeh

Expand-Archive cmdlet 与参数集之一一起使用:

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

A
Abhijit

嘿它为我工作..

$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)
}

如果其中一个文件或目录已经存在于目标位置,它会弹出一个对话框,询问要做什么(忽略、覆盖),这违背了目的。有谁知道如何强制它静默覆盖?
回答@OlegKazakov 的评论:有一组选项控制 CopyHere 方法。我猜@OlegKazakov 已经解决了他的问题。尽管如此,我还是将此链接放在这里以供其他可以找到此主题的冲浪者使用:docs.microsoft.com/en-us/previous-versions/windows/desktop/…
K
Kellen Stuart

使用内置的 powershell 方法 Expand-Archive

例子

Expand-Archive -LiteralPath C:\archive.zip -DestinationPath C:\

m
mikemaccana

使用 expand-archive 但自动创建以存档命名的目录:

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

这必然会在当前目录中展开,不是吗?
并没有真正看到自动创建的附加值。在接受的答案中添加第二个参数 outputPath 会更加灵活。在此解决方案中(如 jpmc26 所说),您将始终在当前目录中创建一个新目录,因此您可能需要在调用 unzip 之前设置当前目录
大多数存档器提取到以存档命名的目录中,与存档位于同一位置。如果您想要不同的东西,没有什么可以阻止您添加参数,但这是一个明智的默认设置。
M
Matej Ridzon

对于那些想要使用 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.applicon 将不起作用。

注意:以这种方式提取档案需要很长时间,并且会减慢 windows gui


u
user1624251
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
T
THess

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
    }