我有一个.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 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医生

其他回答

下面是一个使用system . io . compress . 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)

在PowerShell v5+中,有一个内置的Expand-Archive命令(以及Compress-Archive):

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

使用扩展-归档cmdlet的参数设置之一:

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

对于那些想要使用Shell.Application.Namespace.Folder.CopyHere()并且想要在复制时隐藏进度条,或者使用更多选项的人,文档在这里: https://learn.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)

Shell的使用限制。应用程序在windows核心版本: https://learn.microsoft.com/en-us/windows-server/administration/server-core/what-is-server-core

在windows核心版本中,默认情况下不会安装Microsoft-Windows-Server-Shell-Package,因此shell。应用程序将无法工作。

注意:以这种方式提取档案会花费很长时间,并且会降低windows gui的速度

嘿,它为我工作..

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