Skip to content

Instantly share code, notes, and snippets.

@jahands
Created June 18, 2015 20:22
Show Gist options
  • Save jahands/725cb95ebfa618f93a34 to your computer and use it in GitHub Desktop.
Save jahands/725cb95ebfa618f93a34 to your computer and use it in GitHub Desktop.
Function ArchiveFiles
{
# Params.
param(
[string]$Source,
[int]$Depth,
[string]$Dest,
[switch]$DeleteOriginal,
[switch]$FoldersOnly,
[switch]$SkipFileList
)
if(!$Dest){
$Dest = $Source + "_out"
}
# Create output directory.
if(!(Test-Path -Path $Dest )){
New-Item -ItemType directory -Path $Dest
}
$allFiles = Get-ChildItem -Recurse -Depth $Depth $Source
# Export file list.
$fileListDest = $Dest + "\_file_list.csv"
if(!$SkipFileList.IsPresent){
Export-Csv $fileListDest -InputObject $allFiles
}
#Make sure it's in same format as $items
$allFiles = Select-Object -InputObject $allFiles -Property FullName
# Get files/folders to archive.
$levels = "\*" * $Depth
$items = Get-ChildItem $Source$levels | select FullName
Function ArchiveItem{
param([object]$itemToAdd)
$target7zFile = $Dest.ToString() + $itemToAdd.FullName.Replace((Get-Item $Dest).Parent.FullName.ToString(), "") + ".7z"
$sourceFile = $itemToAdd.FullName
echo("Source: ", $sourceFile, "Target: ", $target7zFile)
if($FoldersOnly.IsPresent -and !$itemToAdd.PSIsContainer){
# continue
#TODO: Copy file instead of compressing.
}
7z a -r -t7z -m0=LZMA2 -mmt=2 $target7zFile $sourceFile
$completedItems += $item
if($DeleteOriginal.IsPresent){
Remove-Item $item
}
}
$doneItems = @()
# Process files/folders.
ForEach($item in $items){
ArchiveItem $item
$doneItems += $item
}
# Add remaining files that are not -ge $Depth levels deep.
ForEach($item in $allFiles){
if(!$doneItems.Contains($item) -and !$item.PSIsContainer){
ArchiveItem $item
}
}
}
$sourceDir="C:\Users\geost\OneDrive\PROBOOK10\ForOnlineOnly\sborin"
$destinationDir="C:\Users\geost\OneDrive\PROBOOK10\ForOnlineOnly\sborin_out"
$depth=6
ArchiveFiles $sourceDir $depth
# 7z a -r -t7z -m0=LZMA2 -mmt=2 $destinationDir $sourceDir
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment