-1

Below is my code:

Function ZipOnebyOne{
    $extension = Get-ChildItem $filePath
    foreach ($file in $extension) { 
        $name = $file.name 
        $directory = $file.DirectoryName 
        $zipfile = $name.Replace($fileExtension,".7z") 
        sz a -t7z "$directory\$zipfile" "$directory\$name"      
    }
}

All I want is to zip the files individually in $filePath regardless of their extension. The method above doesn't work.

SPUDERMAN
  • 187
  • 1
  • 1
  • 10
  • 1
    *doesn't work* is a useless problem description. If you don't understand why, call your doctor and say *My body doesn't work. What's wrong and how do I fix it?* and see if you get a diagnosis and treatment. What specific problem are you having with that code? What is the value in `$filePath`? What is `$fileEtension`, and where does it come from? – Ken White Jun 09 '16 at 02:32
  • Possible duplicate of [How to create a zip archive with PowerShell?](http://stackoverflow.com/questions/1153126/how-to-create-a-zip-archive-with-powershell) – xXhRQ8sD2L7Z Jun 09 '16 at 04:06

1 Answers1

0

As @KenWhite said, you don't clearly say what the problem is, but, I took you sample and fixed all the issues I could find. Maybe, this will help you.

Example using PowerShell 5 Compress-Archive function

Function ZipOnebyOne{
    param(
        [Parameter(Mandatory=$true)]
        [string]
        $filepath
    )

    $extension = Get-ChildItem $filePath -File -Recurse
    foreach ($file in $extension) { 

        $name = $file.name 
        $directory = $file.DirectoryName 
        $fileExtension = $file.Extension
        $zipfile = $name.Replace($fileExtension, '.zip') 
        Compress-Archive -Path (Join-Path $directory $name) -DestinationPath (Join-path $directory $zipfile) -Update
    }
}

Example using 7-Zip

Function ZipOnebyOne{
    param(
        [Parameter(Mandatory=$true)]
        [string]
        $filepath
    )

    $7z = 'C:\Program Files\7-Zip\7z.exe'
    $extension = Get-ChildItem $filePath -File -Recurse
    foreach ($file in $extension) { 

        $name = $file.name 
        $directory = $file.DirectoryName 
        $fileExtension = $file.Extension
        $zipfile = $name.Replace($fileExtension, '.7z') 
        $null = & $7z -t7z a (Join-path $directory $zipfile) (Join-Path $directory $name)
    }
}
TravisEz13
  • 2,263
  • 1
  • 20
  • 28