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

时间:2017-12-12 12:28:33

标签: powershell

我的目标是创建以下的PowerShell脚本:

  1. 在目录中提取多个zip文件
  2. 为多种文件类型创建存档zip文件,并且能够将文件添加到zip中(如果已经存在)。
  3. 我无法在PowerShell v4中使用Compress-Archive / Expand-Archive

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

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

    这会在目录"C:\$year\$month\$folder.zip"中创建zip文件,当我再次使用新的'sample'文件运行相同的脚本时,它表示它已经存在。

    我需要修改脚本,说'如果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
    

1 个答案:

答案 0 :(得分:0)

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