How to zip folders and move them with PowerShell


Like so:


$aListOfFoldersToCompress | ForEach-Object {
    
    $pathFolderToCompress = $_.FullName
    $item = Get-Item $pathFolderToCompress
    $date = $item.CreationTime
    $sDate = $date.Year.ToString("0000") + "-" + $date.Month.ToString("00") + "-" + $date.Day.ToString("00")
    Log "Now compressing folder [$pathFolderToCompress] with folder date [$sDate]."
    $pathZipFile = "$pathFolderToCompress.$sDate.zip"
    $compression = [System.IO.Compression.CompressionLevel]::Fastest
    $tfCreateDirectory = $false
    [System.IO.Compression.ZipFile]::CreateFromDirectory($pathFolderToCompress, $pathZipFile, $compression, $tfCreateDirectory)
    if ($?) {
        Log "Successfully compressed [$pathFolderToCompress]."
    } else {
        Log $Error[0]
    }#if
    $tfOKToDelete = (Test-Path $pathZipFile)
    Move-Item $pathZipFile $pathTargetFolder -Force
    if (($?) -and ($tfOKToDelete)) {
        Remove-Item $pathFolderToCompress -Recurse -Force
        if ($?) {
            Log "Moved [$pathZipFile] and removed [$pathFolderToCompress]."
        }#if
    }#if
    
    
}#foreach

You need to define the following variables and functions:

  • aListOfFoldersToCompress (an array of strings containing the list of folders you want compressed)
  • Log (a function taking a string that will write that string to your log file or an event log)
  • pathTargetFolder (string path of where you want to zipped folders moved afteer zipping)

Hope this helps.

Comment if I forgot something.

 © Andrew Brehm 2016