Skip to content

Instantly share code, notes, and snippets.

@vnau
Created March 6, 2020 19:07
Show Gist options
  • Save vnau/5aa728702ef822c6b37fd8d5926f5159 to your computer and use it in GitHub Desktop.
Save vnau/5aa728702ef822c6b37fd8d5926f5159 to your computer and use it in GitHub Desktop.
PowerShell script to backup files to ZIP archive excluding specific folders
param([Parameter(Mandatory)]$path)
$ErrorActionPreference = "Stop"
# top path that we want to keep in the source code zip file
$subdir = ""
# location of the zip file
$ZipFile = (Get-Item -Path ".\").FullName+"\"+(Split-Path $path -leaf)+".zip"
# change current directory
Set-Location "$path"
# collecting list of files that we want to archive excluding those that we don't want to preserve
$Files = @(Get-ChildItem "${subdir}" -Recurse -File | Where-Object {$_.PSParentPath -inotmatch "x64|packages|.vs|Win32|node_modules|pkg|pkgobj|Debug|Release"})
$FullFilenames = $files | ForEach-Object -Process {Write-Output -InputObject $_.FullName}
# remove old zip file
if (Test-Path $ZipFile) { Remove-Item $ZipFile -ErrorAction Stop }
#create zip file
Add-Type -AssemblyName System.IO.Compression
Add-Type -AssemblyName System.IO.Compression.FileSystem
$zip = [System.IO.Compression.ZipFile]::Open(($ZipFile), [System.IO.Compression.ZipArchiveMode]::Create)
# write entries with relative paths as names
foreach ($fname in $FullFilenames) {
$rname = $(Resolve-Path -Path $fname -Relative) -replace '\.\\',''
Write-Output $rname
$zentry = $zip.CreateEntry($rname)
$zentryWriter = New-Object -TypeName System.IO.BinaryWriter $zentry.Open()
$zentryWriter.Write([System.IO.File]::ReadAllBytes($fname))
$zentryWriter.Flush()
$zentryWriter.Close()
}
# release zip file
$zip.Dispose()
Set-Location (Split-Path $script:MyInvocation.MyCommand.Path)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment