1

How can I use the PowerShell 5.0 Compress-Archive cmdlet to recursively take any .config files in a directory and zip them up while maintaining the directory structure. Example:

Directory1
    Config1.config
Directory2
    Config2.config

The aim is a single zip file also containing the above directory structure and only config files.

4
  • What do you mean? find a config-file, zip it (only the config-file) and leave the zip-file in the same location as the config-file? Commented Mar 21, 2016 at 16:35
  • I added an illustration. Commented Mar 21, 2016 at 16:38
  • The file-structure was the only clear part tbh. What does the desired output look like? You want one zip file containing all the config files? Or one zip file per config file? Commented Mar 21, 2016 at 16:39
  • A single zip with the above directory structure. Commented Mar 21, 2016 at 17:15

1 Answer 1

3

I would suggest copying the files to a temporary directory and compress that. Ex:

$path = "test"
$filter = "*.config"

#To support both absolute and relative paths..
$pathitem = Get-Item -Path $path

#If sourcepath exists
if($pathitem) {
    #Get name for tempfolder
    $tempdir = Join-Path $env:temp "CompressArchiveTemp"

    #Create temp-folder
    New-Item -Path $tempdir -ItemType Directory -Force | Out-Null

    #Copy files
    Copy-Item -Path $pathitem.FullName -Destination $tempdir -Filter $filter -Recurse

    #Get items inside "rootfolder" to avoid that the rootfolde "test" is included.
    $sources = Get-ChildItem -Path (Join-Path $tempdir $pathitem.Name) | Select-Object -ExpandProperty FullName

    #Create zip from tempfolder
    Compress-Archive -Path $sources -DestinationPath config-files.zip

    #Remove temp-folder
    Remove-Item -Path $tempdir -Force -Recurse
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.