You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用PowerShell实现带密码保护的文件夹压缩?

Password-Protected Folder Compression in 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:

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 -p and 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 of CreateFromDirectory)
  • -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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:55:04