繁体   English   中英

PowerShell v4-存档和提取新的和现有的Zip文件

[英]PowerShell v4 - Archiving and Extracting New & Existing Zip Files

我的目标是创建将执行以下操作的PowerShell脚本:

  1. 提取目录中的多个zip文件
  2. 为多种文件类型创建存档zip文件,并能够将文件添加到zip(如果已存在)。

我无法在PowerShell v4中使用Compress-Archive / Expand-Archive

这会提取test.zip,但我需要使用通配符一次提取多个.zip文件:

[System.IO.Compression.ZipFile]::ExtractToDirectory('C:\test.zip', 'C:\') 

这将在目录"C:\\$year\\$month\\$folder.zip"创建一个zip文件,当我使用新的“样本”文件再次运行同一脚本时,它说该文件已经存在。

我需要将脚本修改为“如果存在zip文件,则将文件添加到其中”。

$year = Get-Date -Format 'Yr. yyyy'
$month = Get-Date -Format 'MMMM'
$folder = Get-Date -Format 'TESTddMMyyyy'
$source = "C:\$year\$month\$folder"
$destination = "C:\$year\$month\$folder.zip"
New-Item -ItemType Directory -Path "C:\$year\$month\$(Get-Date -Format 'TESTddMMyyyy')"
Move-Item 'C:\SAMPLE*' "C:\$year\$month\$(Get-Date -Format 'TESTddMMyyyy')"
Add-Type -assembly "system.io.compression.filesystem"
[system.io.compression.zipfile]::CreateFromDirectory($source, $destination)
$compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal
Remove-Item $source -Force -Recurse
if (Test-Path $destination)
{
   [System.IO.Compression.ZipArchive]$ZipFile = [System.IO.Compression.ZipFile]::Open($destination, ([System.IO.Compression.ZipArchiveMode]::Update))
   [System.IO.Compression.ZipFileExtensions]::CreateEntryFromFile($ZipFile, $source, (Split-Path $source -Leaf))
   $ZipFile.Dispose()
}
else
{
   [system.io.compression.zipfile]::CreateFromDirectory($source, $destination)
   $compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal
}
Remove-Item $source -Force -Recurse

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM