如何使用PowerShell实现带密码保护的文件夹压缩?
Hey there! The built-in .NET System.IO.Compression classes your current code uses don't support password-protected ZIP files natively. To add password protection, we'll need to leverage a third-party tool with command-line support—7-Zip (free and open-source) is a great choice, and WinRAR works too. Here are step-by-step implementations for both:
Option 1: Use 7-Zip (Recommended, Free)
First, make sure 7-Zip is installed on your system. By default, it installs to C:\Program Files\7-Zip\7z.exe—adjust the path if yours is different.
Here's the PowerShell code to compress your folder with a password:
$source = "C:\tmp\repertoire" $destination = "C:\tmp\repertoire.zip" $password = "YourSecurePasswordHere" # Avoid hardcoding this in production! # Path to 7-Zip executable $7zipPath = "C:\Program Files\7-Zip\7z.exe" # Run 7-Zip command to create password-protected ZIP & $7zipPath a -p"$password" -mx=5 -mhe=on "$destination" "$source"
Breakdown of the 7-Zip parameters:
a: Tells 7-Zip to add files/folders to the archive-p"$password": Sets the password for the archive (no space between-pand the password)-mx=5: Sets compression level (5 is balanced; 0=store, 9=max compression)-mhe=on: Enables encryption of the archive's filename list (optional but adds extra security)
Option 2: Use WinRAR
If you have WinRAR installed (default path: C:\Program Files\WinRAR\WinRAR.exe), you can use this approach:
$source = "C:\tmp\repertoire" $destination = "C:\tmp\repertoire.zip" $password = "YourSecurePasswordHere" # Path to WinRAR executable $winRarPath = "C:\Program Files\WinRAR\WinRAR.exe" # Run WinRAR command to create password-protected ZIP & $winRarPath a -ep1 -p"$password" -r "$destination" "$source"
WinRAR parameter breakdown:
a: Add files to archive-ep1: Exclude the base folder path from the archive (matches the behavior ofCreateFromDirectory)-p"$password": Set the archive password-r: Recurse subfolders
Important Security Note:
Never hardcode passwords directly in your script! For production use, consider reading the password from a secure source like:
- User input with
Read-Host -AsSecureString(then convert to plaintext if needed) - A secure vault (like Windows Credential Manager)
- An environment variable set securely
内容的提问来源于stack exchange,提问作者Idriss Bediss

