0

I have a statement in my power shell script that archives all files in a directory to a given path:

[System.IO.Compression.ZipFile]::CreateFromDirectory($sourcePath,$destPath, $compressionLevel, $false);

What I want to is to instead of archiving whole directory just archive items that I selected through this statement:

Get-ChildItem $sourcePath -include *.txt,*.log | Where-Object { $_.CreationTime -le $archiveTillDate } 

So how is it possible to pass a specific set of files as a parameter to CreateFromDirectory instead of path to whole directory?

Maven
  • 14,587
  • 42
  • 113
  • 174

1 Answers1

2

Add selected files to a new or existing zip archive

Add-Type -AssemblyName System.IO.Compression.FileSystem            
$CompressionLevel = [System.IO.Compression.CompressionLevel]::Optimal


$SourceFiles = Get-Childitem C:\TestLogs2\*.csv 
$ZipFile = 'C:\TestFiles\testzip1.zip'
$Zip = [System.IO.Compression.ZipFile]::Open($ZipFile,'Create')  

ForEach ($SourceFile in $SourceFiles) 
  {
    $SourcePath = $SourceFile.Fullname
    $SourceName = $SourceFile.Name
    $null = [System.IO.Compression.ZipFileExtensions]::
             CreateEntryFromFile($Zip,$SourcePath,$SourceName,$CompressionLevel)
  }

$Zip.Dispose()

The 'Update' method will open an existing zip file for update, or create a new file if the specified file doesn't exit.

There is also an 'Create' method that will create an new zip file but will throw an error if the file already exists.

mjolinor
  • 66,130
  • 7
  • 114
  • 135