Compress Multiple Files\Folders and encrypt zip with password via Powershell

Viewed 1788

I'm Trying to make a quick script in powershell that will compress multiple folder (or files doesnt matter for now, in my example its folders) and add to each zip file a random password and export the passwords for each zip file, to csv.

This is what i got so far...

$path = "\\path\of\folders"
$source = Get-ChildItem -Path \\path\of\folders -Filter "*?" -Directory

Add-Type -assembly "system.io.compression.filesystem"

Foreach ($s in $source){
    $destination = Join-path -path $path -ChildPath "$($s.name).zip"

    If(Test-path $destination) {Remove-item $destination}

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

with this i'm able to compress each folder in the main folder, to zip files each with its name.

where i get complicated to manage, is how to add a random password for each of the zip files... and after that i'll just add | Export-Csv -Path \to\my\path\passwords.csv (unless im wrong about that export)

any ideas on that?

Thanks!

1 Answers

managed to work out a script that compressing and encrypting the zip files.

 if (-not (Test-Path "C:\Program Files\7-Zip\7z.exe")){
    Write-Warning "C:\Program Files\7-Zip\7z.exe needed"
}

Add-Type -AssemblyName System.Web
$7z = ("C:\Program Files\7-Zip\7z.exe")

foreach($subfolder in (Get-ChildItem "\\path_of_directoris" -Directory))
{
    $pass =  [System.Web.Security.Membership]::GeneratePassword(10,2) 
    $Source    = $subfolder.fullname 
    $Target    = "\\path_of_directoris\$($subfolder.name).zip"
    & $7z "a" "-mx=9" "$Target" "$Source" "-p$pass" | Export-CSV -Path "\\path_to_store_pass\passwords.csv"
    echo $subfolder, $pass
}
 
Related