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

PowerShell中将多个文件夹打包到单个压缩文件的问题

Fixing Your PowerShell Directory Compression Script

Hey there, let's work through this since you're new to PowerShell! I noticed your script cuts off mid-loop, so I'll fill in the gaps, fix potential pitfalls in your existing code, and explain everything step by step.

First, let's start with a complete, tested version of the script that does exactly what you want: backs up the App_Config, Resources, and bin directories from your dev82 site, saves them to C:\backup\DEV82 with a timestamp, and handles edge cases like missing directories.

Complete Working Script

# Define key paths and target directories
$backupRoot = "C:\backup\DEV82"
$sourceSiteRoot = "C:\inetpub\wwwroot\dev82"
$directoriesToBackup = @("App_Config", "Resources", "bin")

# Create backup directory if it doesn't exist
if (-not (Test-Path -Path $backupRoot -PathType Container)) {
    New-Item -ItemType Directory -Path $backupRoot | Out-Null
    Write-Host "Created backup directory at $backupRoot"
}

# Get the actual directories we want to back up (skip any that don't exist)
$targetDirs = Get-ChildItem -Path $sourceSiteRoot -Directory | 
              Where-Object { $directoriesToBackup -contains $_.Name }

# Exit early if no target directories were found
if (-not $targetDirs) {
    Write-Warning "Warning: None of the target directories ($($directoriesToBackup -join ', ')) were found in $sourceSiteRoot"
    exit 1
}

# Generate a timestamp for unique backup filenames
$timeStamp = (Get-Date).ToString("yyyyMMdd_HHmmss")

# Load the .NET compression assembly (required for zip operations)
Add-Type -AssemblyName System.IO.Compression.FileSystem

# Option 1: Compress each directory into its own zip file
foreach ($dir in $targetDirs) {
    $zipFilePath = Join-Path -Path $backupRoot -ChildPath "$($dir.Name)_$timeStamp.zip"
    
    try {
        # Create zip from directory (Optimal compression, exclude top-level folder from zip)
        [System.IO.Compression.ZipFile]::CreateFromDirectory(
            $dir.FullName,
            $zipFilePath,
            [System.IO.Compression.CompressionLevel]::Optimal,
            $false
        )
        Write-Host "✅ Successfully compressed $($dir.Name) to $zipFilePath"
    }
    catch {
        Write-Error "❌ Failed to compress $($dir.Name): $_"
    }
}

# Option 2: Combine all three directories into a single zip file (uncomment to use)
# $combinedZipPath = Join-Path -Path $backupRoot -ChildPath "Dev82_FullBackup_$timeStamp.zip"
# try {
#     [System.IO.Compression.ZipFile]::CreateFromDirectory(
#         $sourceSiteRoot,
#         $combinedZipPath,
#         [System.IO.Compression.CompressionLevel]::Optimal,
#         $true,
#         $null,
#         $directoriesToBackup
#     )
#     Write-Host "✅ Successfully created combined backup at $combinedZipPath"
# }
# catch {
#     Write-Error "❌ Failed to create combined backup: $_"
# }

What Was Wrong With Your Original Script?

Let's break down the issues in your initial code to help you avoid them in the future:

  • Unreliable directory switching: Using cd in scripts is risky—if the path doesn't exist or you lack permissions, the script will fail silently. We use absolute paths instead for consistency.
  • Imprecise directory filtering: Your Where-Object {$_.FullName -match "App_Config|Resources|bin"} could accidentally match directories with those strings in their full path (not just their name). Using -contains with a list of exact directory names is safer.
  • Incomplete loop: Your script cut off at Foreach ($s—we filled in the compression logic using .NET's ZipFile class, which is the most reliable way to handle zips in PowerShell.
  • No error handling: We added try/catch blocks to catch and report any issues during compression (like permission errors or locked files).
  • No validation: We check if target directories exist before trying to compress them, so you get a clear warning instead of a silent failure.

How to Use This Script

  1. Copy the script into a .ps1 file (e.g., Backup-Dev82Directories.ps1)
  2. Run it in PowerShell (make sure your execution policy allows script execution—run Set-ExecutionPolicy RemoteSigned if needed, then confirm)
  3. Choose between Option 1 (individual zips) or Option 2 (single combined zip) by uncommenting the relevant section

内容的提问来源于stack exchange,提问作者Vasyl Stepulo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 07:45:29