Powershell system.io.compression zipping files and/or Folders

32,942

@DavidBrabant is right that it is not normal to put the wildcard in the path, but I think you can get away with it in this instance as you are piping the results through a foreach statement.

I believe the problem is that your first parameter of CreateFromDirectory should be a directory name, but you have passed it a filename. This isn't really helped by the use of variable names ($Source and $source).

When you call CreateFromDirectory it will contain the full name to the first zip file because of the following line:

$Source = $_.fullName

I'm guessing that as you have a filter '*.txt' you want to add individual files rather than the whole folder to a zip file then it is a little more involved. See here for an example: http://msdn.microsoft.com/en-us/library/hh485720(v=vs.110).aspx

But if you simply want to zip the folder then use:

$sourceFolder = "C:\folder1"
$destinationZip = "c:\zipped.zip" 
[Reflection.Assembly]::LoadWithPartialName( "System.IO.Compression.FileSystem" )
[System.IO.Compression.ZipFile]::CreateFromDirectory($sourceFolder, $destinationZip)
Share:
32,942
vya
Author by

vya

Updated on November 20, 2020

Comments

  • vya
    vya over 3 years

    Im producing some automated tasks at work where i need to zip certain files and/or folders. What im trying to do is getting zip the text files in folder 1 which contains 4 txt files.

    Executing this command gives an error but still zips the txt files :

    Exception calling "CreateFromDirectory" with "4" argument(s): "The directory name is invalid.
    "
    At line:15 char:13
    +             [System.IO.Compression.ZipFile]::CreateFromDirectory($Source, "$Sour ...
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    

    What i got now is:

    [Reflection.Assembly]::LoadWithPartialName( "System.IO.Compression.FileSystem" )
    $includeBaseDirectory = $false
    $compressionLevel= [System.IO.Compression.CompressionLevel]::Optimal
    
    $source = "C:\folder1\*"
    Get-ChildItem $source -include *.txt  |
    Foreach {
            $Source = $_.fullName
            [System.IO.Compression.ZipFile]::CreateFromDirectory    ($Source, "$Source.zip",$compressionLevel, $includebasedirectory)
            }
    

    Also if i want to zip the folders inside folder1 i use -directory switch instead of include. that doesnt produce any error messages. any suggestions?