Search code examples
powershellarchive7zip

Powershell folder archiving


I have a powershell script that simply uses the Get-ChildItem command to search through a directory for a folder matching a keyword. When found I need it to zip it and leave it right in that same directory.

Here's what I've tried by piping the command into both 7zip and the native compress:

    set-alias zip "$env:ProgramFiles\7-Zip\7z.exe"
    Get-ChildItem $path "keyword" -Recurse -Directory | zip a
AND
    Get-ChildItem $path"keyword" -Recurse -Directory | compress-archive

Both times it always asks for a source and destination which is hard to define since I'm having it search through a drive with many sub-folders. I though using the pipe would imply the source as well.

Any ideas? Thanks!

EDIT:

I suppose I could set the Get-ChildItem to a variable and use that as the "source" and have the destination be a generic location for them all but I'd have to name them differently, no?


Solution

  • Give this a try:

    $path = "INSERT SOURCE ROOT"
    
    foreach ($directory in Get-ChildItem $path -Recurse -Directory -Filter "keyword"| Select-Object FullName | foreach { $_.FullName}) {
        $destination = Split-Path -Path $directory -Parent
    
        Compress-Archive -Path $directory -DestinationPath $destination
    
    }
    
    

    This is looking inside the path for anything matching the "keyword", going up 1 level, and then zipping the found file.