简体   繁体   中英

PowerShell v4 - Archiving and Extracting New & Existing Zip Files

I'm aiming to create PowerShell scripts that will:

  1. Extract multiple zip files in a directory
  2. Create archive zip files for multiple file types with the ability to add files to the zip if it already exists.

I cannot use Compress-Archive / Expand-Archive in PowerShell v4

This extracts test.zip but I need it to extract multiple .zip files at once using a wildcard:

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

This creates the zip file in the directory "C:\\$year\\$month\\$folder.zip" , When I run the same script again with a new 'sample' file, it says it already exists.

I need to amend the script to say 'If the zip file exists, add the file to it'.

$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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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