1

Question: Can Powershell automatically create an individual zipped archive file for each object that it finds within a directory?

Background:

  • A directory with a couple of hundred files in it (various file types)
  • I need to create a zipped archive for each one of them.

Concept Workflow:

  1. Powershell Script is pointed to a directory
  2. Powershell discovers a bunch of files (various extensions)
  3. Powershell automatically compresses "Widget.CFG" into a .ZIP file
  4. Process repeats against every other object found within that same directory

Environment:

  • Windows 7/64 Bit OS
  • Powershell version 5 (Major: 5 Minor: 1 Build: 15363 Revision:786)

Is this possible?

The script I have come up with (below) does not produce any outputs, and I'm stumped as to why.

What I have so far:

$Path = "C:\ziptest"   

function Compress-ChildItem {   
    [CmdletBinding()]   
    param(   
        [Parameter(Position = 0, Mandatory, ValueFromPipeline)]   
        [ValidateNotNull()]   
        [System.IO.DirectoryInfo[]]   
        $Path   
    )   
    process {   
        Get-ChildItem -File $Path | ForEach-Object {   
            $NewName = "{0}-{1}.zip" -f $_.BaseName, ($_.Extension -replace '.')   
            $CompressionParams = @{   
                DestinationPath = Join-Path $Path -ChildPath $NewName   
                Path = $_.FullName   
            }   
            Compress-Archive @CompressionParams   
        }   
    }   
}    
  • What version of PowerShell and Windows would this be used on? – Jeff Zeitlin Mar 15 '18 at 16:24
  • - Windows 7/64 Bit OS - Powershell version 5 (Major: 5 Minor: 1 Build: 15363 Revision:786) – TPK Mar 15 '18 at 16:41
  • 1
    Yes, it is possible, but please note that superuser.com is not a free script/code writing service. If you tell us what you have tried so far (include the scripts/code you are already using) and where you are stuck then we can try to help with specific problems. You should also read How do I ask a good question?. – DavidPostill Mar 15 '18 at 16:45
  • 1
    While @DavidPostill is quite correct in his comment, I will offer you some basic assistance to get started: I commend your attention to this Hey, Scripting Guy! and Microsoft's documentation on the Compress-Archive cmdlet. – Jeff Zeitlin Mar 15 '18 at 17:04
  • @DavidPostill - Edited post as requested. Please remove the hold? – TPK Mar 15 '18 at 19:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.