2

I'm new to Powershell. I have a need that I assumed that it would be perfect for. However, I've quickly come to the point where I feel I'm in over my head. Basically, I need to create a .zip file.

I have a directory that looks like the following:

MyStuff
  Dir1
    Child1
      File1.txt
    Child2
      File1.png
    Child3
      File1.txt
  Dir2
    File1.txt
  File1.txt
  File2.txt
  File3.txt
  ...

I need to create a .zip file named bundle.zip. Bundle.zip should NOT have all of the files inside of MyStuff. Instead, I need to include MyStuff/File1.txt, MyStuff/File2.txt, MyStuff/File3.txt, and MyStuff/Dir1/* into the .zip file. I have no idea how to do this with PowerShell.

I have PowerShell v1.0 installed on my machine. I've been trying "Write-Zip" from the PowerShell Community Extensions, however, I get an error that says: "The term 'Write-Zip' is not recognized as the name of a cmdlet, function, script file, or operable program".

What am I doing wrong?

10
  • 1
    I'd start by suggesting that you upgrade powershell if you can, v1.0 is relatively old and I believe things have changed rather dramatically between then and now. That being said that error sounds like you just haven't loaded the extension correctly. Jul 30, 2013 at 18:48
  • As it turns out, I have version 3 installed. I've confirmed this by running $Host.version from the powershell prompt. For some reason, MS just kept it in the v1.0 direction :/
    – user26712
    Jul 30, 2013 at 19:27
  • How did you install/load the extension you are trying to use? Does Get-Command Write-Zip find the command? What about Get-Module <the extension module>? Jul 30, 2013 at 19:51
  • Get-Command Write-Zip and Get-Module pscx both work from the command line just fine.
    – user26712
    Jul 30, 2013 at 20:28
  • So in a single powershell session you can run Get-Command Write-Zip and it finds the function but if you then try to run Write-Zip it fails with the error in your post? Jul 30, 2013 at 21:23

2 Answers 2

1

You need to download the Powershell Community Extension compatible with your installed Powershell version and install the same. Once the installation is done You need to move the PSCX module from the Program files location to the Powershell Module and then try using Write-Zip command.

https://pscx.codeplex.com/releases/view/133199

1
  • Emphasis on "compatible with your installed version..." not sure what version of PSCX is compatible with PS v1.0, but it's not the latest one.
    – Ryan Ries
    Aug 14, 2015 at 12:20
1

Zipping can be done using the CreateFromDirectory method of the .NET class System.IO.Compression.ZipFile. I prefer using .NET over installing community extensions and other add-ons, in order to keep the server environment as clean as possible.

I believe you cannot use it to add to a zip archive, but would need to temporarily copy the files and folders in the correct structure to a staging directory. From there you could create the zip file and delete the staging content.

To use .NET for zipping you first need to load the class assembly:

[System.Reflection.Assembly]::LoadWithPartialName("System.IO.Compression.FileSystem")

Then you can call the class:

[System.IO.Compression.ZipFile]::CreateFromDirectory($DirPath, $ZipFilePath, $CompressionLevel, $includeBaseDir)

Where:

$DirPath is the directory you want to zip.

$ZipFilePath is the name of the zipfile you want to create.

$Compressionlevel can be set to Optimal, Fastest or NoCompression.

$includeBaseDir can be $true or $false.

I wrote a function out of it to save me the bother of having to look up the .NET reference page all the time. If you look at the page you will see there is a method for unzipping too.

.NET 4.5 is required and I would strongly encourage you to upgrade powershell too. Every version has brought massive improvements. It also turns out using .NET is efficient, having benchmarked it against popular 3rd party zip applications it comes out strongly.

The function is pretty self explanatory, just make sure you run the function itself before calling it. Here is a short syntax rundown if you need it:

New-ZipFile {DirToZip} {ZipfilePathAndName} {fastORoptimalORnocompression} {IncludeBaseDirectoryInZip($true or $false)}

So to zip E:\stuff to D:\zipfile.zip using optimal compression and include the basedir .\stuff in the zipfile, you would run:

New-ZipFile 'E:\stuff' 'D:\zipfile.zip' Optimal $true

Here is the function:

#region function New-ZipFile
<#
.Synopsis
   Creates a zip file from a directory.
.DESCRIPTION
   Creates a zip file from a directory. Options include compression level and wether or not to include the base directory. Class reference: https://msdn.microsoft.com/en-us/library/hh875104(v=vs.110).aspx
.EXAMPLE
   New-ZipFile c:\dir c:\zipfile.zip Fastest $True
.EXAMPLE
   New-ZipFile c:\dir c:\zipfile.zip Optimal $True
.INPUTS
   Inputs to this cmdlet (if any)
.OUTPUTS
   Output from this cmdlet (if any)
.NOTES
   General notes
.COMPONENT
   The component this cmdlet belongs to
.ROLE
   The role this cmdlet belongs to
.FUNCTIONALITY
   The functionality that best describes this cmdlet
#>
function New-ZipFile
{
    Param
    (
        # The directory to zip.
        [Parameter(Mandatory=$true, 
                   Position=0)]
        [ValidateNotNullOrEmpty()]
        [string]$DirPath,

        # The zipfile name.
        [Parameter(Mandatory=$true, 
                   Position=1)]
        [ValidateNotNullOrEmpty()]
        [string]$ZipFilePath,

        # Specifies values that indicate whether a compression operation emphasizes speed or compression size.
        [Parameter(Mandatory=$true, 
                   Position=2)]
        [ValidateNotNullOrEmpty()]
        [ValidateSet("Fastest", "NoCompression", "Optimal", ignorecase=$True)]
        [string]$CompressionLevel,

        # $True to include the directory name from sourceDirectoryName at the root of the archive; $False to include only the contents of the directory.
        [Parameter(Mandatory=$true, 
                   Position=3)]
        [ValidateNotNullOrEmpty()]
        [bool]$includeBaseDir
          )

    #Load the .NET 4.5 zip-assembly
    [System.Reflection.Assembly]::LoadWithPartialName("System.IO.Compression.FileSystem") | Out-Null
    # Zip the directory.
    [System.IO.Compression.ZipFile]::CreateFromDirectory($DirPath, $ZipFilePath, $CompressionLevel, $includeBaseDir)
}
#endregion

EDIT: The Scripting guy wrote an article where he shows an alternative way of loading the assembly, it's a bit cleaner looking.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .