Leanne Kami
Leanne Kami

Reputation: 89

Archive files one by one in a directory with 7-Zip and doing so for each subfolders with PowerShell

I have the following directory structure.

 /Data
 - file 1
 - file 2

  /Folder1

   - file 3
   - file 4

  /Folder2
   - file 5
   - file 6

    /Folder3
      - file 7
      - file 8

With many files with extensions such as .csv, .xls, .bak, .sav etc

I am trying to get a PowerShell script that would do the following steps:

  1. Zip all the files one by one with the .7z level of compression
  2. Proceed to each directory but create the .7z to the current directory the files are
  3. Delete the original file once compressed and keep the compressed file only

It would end up like this afterwards.

/Data
- file 1.7z
- file 2.7z

    /Folder1
    - file 3.7z
    - file 4.7z

    /Folder2
    - file 5.7z
    - file 6.7z

    /Folder3
    - file 7.7z
    - file 8.7z

My script so far is pretty simple but also not complete. I didn't managed to make it work through all subdirectories, it only applies to /Data level so far. I also need to figure out how to delete the original file once it has been compressed. Any help would be much appreciated.

Set-Location C:\Temp\Test_zip
Get-ChildItem -Include *.csv, *.xlsx, *.xls, *.sav, *.parquet, *.bak, *.dmp, *txt, *.pkl -Recurse | ForEach-Object { & "C:\Program Files\7-Zip\7z.exe" a -tzip ($_.Name+".7z") $_.Name }
$sz = ("C:\Program Files\7-Zip\7z.exe")
Start-Process $sz -argumentList "a", "-mx=9", "-r"

Upvotes: 1

Views: 1476

Answers (2)

Ken Teo
Ken Teo

Reputation: 11

Some enhancements made Frenchy's excellent codes as 7z already has an option to remove the file after compress and to remove the extenstion from the zipped file.

Get-ChildItem -Path D:\Test -Include *.txt -Recurse |
ForEach-Object {
    $result = & "C:\Program Files\7-Zip\7z.exe" a -mx9 -t7z -sdel ( $_.Name -replace '\.txt','.7z' ) $_.Name
}

Upvotes: 1

Frenchy
Frenchy

Reputation: 17037

i suggest you to use fullName instead Name to avoid errors if you have more folders to scan, and in your loop add the remove-itm to delete the original file:

Set-Location C:\Temp\Test_zip
Get-ChildItem -Include *.csv, *.ps1, *.xls, *.text, *.parquet, *.bak, *.dmp, *txt, *.pkl -Recurse | 
ForEach-Object { 
    $result = & "C:\Program Files\7-Zip\7z.exe" a -tzip ($_.FullName+".7z") $_.FullName 
    Remove-Item $_.FullName 
}

Upvotes: 2

Related Questions