Add-Type -A System.IO.Compression.FileSystem
[IO.Compression.ZipFile]::CreateFromDirectory('foo', 'foo.zip')
[IO.Compression.ZipFile]::ExtractToDirectory('foo.zip', 'bar')
我从这个答案中找到了通过PowerShell创建和提取.zip文件的代码,但由于我的声誉不佳,我无法提出问题作为对该答案的评论。
- 创建 - 如何在没有用户交互的情况下覆盖现有的.zip文件?
- 提取 - 如何在没有用户交互的情况下覆盖现有文件和文件夹?(最好像机器人副本
mir
功能(。
PowerShell 具有内置的.zip
实用工具,无需在版本 5 及更高版本中使用 .NET 类方法。Compress-Archive
-Path
参数也采用string[]
类型,因此您可以将多个文件夹/文件压缩到目标 zip 中。
压缩:
Compress-Archive -Path C:Foo -DestinationPath C:Foo.zip -CompressionLevel Optimal -Force
还有一个-Update
开关。
解压缩:
Expand-Archive -Path C:Foo.zip -DestinationPath C:Foo -Force
5 之前的 PowerShell 版本可以执行此脚本
感谢 @Ola-M 的更新。
感谢@maximilian-Burszley的更新。
function Unzip($zipfile, $outdir)
{
Add-Type -AssemblyName System.IO.Compression.FileSystem
$archive = [System.IO.Compression.ZipFile]::OpenRead($zipfile)
try
{
foreach ($entry in $archive.Entries)
{
$entryTargetFilePath = [System.IO.Path]::Combine($outdir, $entry.FullName)
$entryDir = [System.IO.Path]::GetDirectoryName($entryTargetFilePath)
#Ensure the directory of the archive entry exists
if(!(Test-Path $entryDir )){
New-Item -ItemType Directory -Path $entryDir | Out-Null
}
#If the entry is not a directory entry, then extract entry
if(!$entryTargetFilePath.EndsWith("")){
[System.IO.Compression.ZipFileExtensions]::ExtractToFile($entry, $entryTargetFilePath, $true);
}
}
}
finally
{
$archive.Dispose()
}
}
Unzip -zipfile "$zip" -outdir "$dir"