Vasyl Stepulo
Vasyl Stepulo

Reputation: 1603

Add multiple folders in one zip file in Powershell

Perhaps my question can be a duplicate, but I'm new in powershell, and cannot figure out, what is wrong with my script, that zipping particular directories:

$path = "C:\backup\DEV82" 
if(!(Test-Path -Path $path )){
    New-Item -ItemType directory -Path $path
}

cd C:\inetpub\wwwroot\dev82\


$SOURCE = Get-ChildItem * -Directory|Where-Object {$_.FullName -match "App_Config|Resources|bin"}

$dtstamp = (Get-Date).ToString("yyyyMMdd_HHmmss")

Add-Type -assembly "system.io.compression.filesystem"
Foreach ($s in $SOURCE)
{
    $DESTINATION = Join-path -path $path -ChildPath "$dtstamp.zip"
    If(Test-path $DESTINATION) {
        Remove-item $DESTINATION
    }
    [io.compression.zipfile]::CreateFromDirectory($s.fullname, $DESTINATION)
}

If I execute command in $SOURCE variable, it gathers all required directories, which I want zip http://prntscr.com/j0sqri

$DESTINATION also returns valid value

PS C:\> $DESTINATION
C:\backup\DEV82\20180404_223153.zip

but right now only last folder (Resources) exists in zip file.

Upvotes: 3

Views: 6413

Answers (2)

Vasyl Stepulo
Vasyl Stepulo

Reputation: 1603

Ok, I rewrite my script, using, instead of Zipfile class, Compress-Archive with -Update ( -Update allows to add files\folders into existing archive )

$path = "C:\backup\DEV82" 
if(!(Test-Path -Path $path )){
    New-Item -ItemType directory -Path $path
}

cd C:\inetpub\wwwroot\dev82\
$SOURCE = Get-ChildItem * -Directory|Where-Object {$_.FullName -match "App_Config|Resources|bin"}

$dtstamp = (Get-Date).ToString("yyyyMMdd_HHmmss")
$DESTINATION = Join-path -path $path -ChildPath "$dtstamp.zip"
Add-Type -assembly "system.io.compression.filesystem"
If(Test-path $DESTINATION) {
    Remove-item $DESTINATION
}

Foreach ($s in $SOURCE)
{
Compress-Archive -Path $s.fullname -DestinationPath $DESTINATION -Update
}

Upvotes: 4

boxdog
boxdog

Reputation: 8442

$SOURCE is already just a list of folder names, so you don't need the FullName property here:

[io.compression.zipfile]::CreateFromDirectory($s.fullname, $DESTINATION)

Either remove it, or remove the Select-Object from the pipeline here:

$SOURCE = Get-ChildItem * -Directory | 
            Where-Object {$_.FullName -match "App_Config|Resources|bin"} |
                Select-Object -ExpandProperty FullName

Upvotes: 1

Related Questions