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
cdin 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-containswith 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'sZipFileclass, which is the most reliable way to handle zips in PowerShell. - No error handling: We added
try/catchblocks 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
- Copy the script into a
.ps1file (e.g.,Backup-Dev82Directories.ps1) - Run it in PowerShell (make sure your execution policy allows script execution—run
Set-ExecutionPolicy RemoteSignedif needed, then confirm) - Choose between Option 1 (individual zips) or Option 2 (single combined zip) by uncommenting the relevant section
内容的提问来源于stack exchange,提问作者Vasyl Stepulo
相关产品推荐
相关产品推荐

