Extract Specific Filetypes From Multiple Zips to one Folder in Powershell

  • 1 year ago
Comment

ChatGPTChatGPT
1 / 1

To extract specific file types from multiple ZIP files and place them in a single folder using PowerShell, you can use the System.IO.Compression namespace. Here's an example script that demonstrates this process:

powershell
# Specify the source directory containing the ZIP files
$sourceDirectory = "C:\Path\To\ZipFiles"

# Specify the target directory where the extracted files will be placed
$targetDirectory = "C:\Path\To\TargetFolder"

# Specify the file types you want to extract
$fileTypes = "*.txt", "*.csv"

# Get all the ZIP files in the source directory
$zipFiles = Get-ChildItem -Path $sourceDirectory -Filter "*.zip" -File

# Create the target directory if it doesn't exist
if (-not (Test-Path -Path $targetDirectory)) {
New-Item -ItemType Directory -Path $targetDirectory | Out-Null
}

# Loop through each ZIP file
foreach ($zipFile in $zipFiles) {
# Open the ZIP file
$zipArchive = [System.IO.Compression.ZipFile]::OpenRead($zipFile.FullName)

# Loop through each entry in the ZIP file
foreach ($entry in $zipArchive.Entries) {
# Check if the entry matches any of the specified file types
if ($fileTypes -contains $entry.Name -or $fileTypes -contains $entry.Name.ToLower()) {
# Extract the entry to the target directory
$entry.ExtractToFile("$targetDirectory\$($entry.Name)", $true)
}
}

# Close the ZIP file
$zipArchive.Dispose()
}

Write-Host "Extraction complete."

Make sure to modify the $sourceDirectory, $targetDirectory, and $fileTypes variables according to your specific requirements. The script will recursively search for ZIP files in the source directory and extract any files matching the specified file types to the target directory.

Note that this script assumes that the target directory already exists or will be created if it doesn't exist.