aethercyn

Untitled

Sep 4th, 2025 (edited)
625
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PowerShell 5.37 KB | Software | 0 0
  1. <#
  2. .SYNOPSIS
  3. Extracts a specific folder and its contents from a ZIP archive.
  4.  
  5. .DESCRIPTION
  6. This PowerShell script extracts a folder from a ZIP archive and is directly executable.
  7. It can extract a folder in one of two ways:
  8. 1. By providing the full, known path to the folder within the ZIP file using -FolderPathInZip.
  9. 2. By searching for a folder by its name anywhere within the ZIP archive using -FindFolderByName.
  10.  
  11. .PARAMETER ZipFilePath
  12. The full path to the source .ZIP file.
  13.  
  14. .PARAMETER FolderPathInZip
  15. (ParameterSet: ByPath) The full path to the folder inside the ZIP file that you want to extract. e.g., 'path/to/MyFolder'.
  16.  
  17. .PARAMETER FindFolderByName
  18. (ParameterSet: ByName) The name of the folder to search for and extract. The script will extract the first match it finds. e.g., 'MyFolder'.
  19.  
  20. .PARAMETER DestinationPath
  21. The path to the directory where the folder should be extracted.
  22.  
  23. .EXAMPLE
  24. # Example 1: Extracting by known full path
  25. PS C:\> .\Extract-SpecificFolderFromZip.ps1 -ZipFilePath "C:\archive.zip" -FolderPathInZip "data/logs/today" -DestinationPath "C:\temp"
  26.  
  27. # Example 2: Searching for a folder by name
  28. PS C:\> .\Extract-SpecificFolderFromZip.ps1 -ZipFilePath "C:\archive.zip" -FindFolderByName "today" -DestinationPath "C:\temp"
  29. #>
  30. [CmdletBinding(DefaultParameterSetName='ByPath')]
  31. param(
  32.     [Parameter(Mandatory=$true)]
  33.     [string]$ZipFilePath,
  34.  
  35.     [Parameter(Mandatory=$true, ParameterSetName='ByPath')]
  36.     [string]$FolderPathInZip,
  37.  
  38.     [Parameter(Mandatory=$true, ParameterSetName='ByName')]
  39.     [string]$FindFolderByName,
  40.  
  41.     [Parameter(Mandatory=$true)]
  42.     [string]$DestinationPath
  43. )
  44.  
  45. try {
  46.     # Add the required .NET assembly to work with ZIP files
  47.     Add-Type -AssemblyName System.IO.Compression.FileSystem
  48.  
  49.     if (-not (Test-Path $ZipFilePath -PathType Leaf)) {
  50.         Write-Error "The specified ZIP file does not exist: $ZipFilePath"
  51.         return
  52.     }
  53.  
  54.     if (-not (Test-Path $DestinationPath -PathType Container)) {
  55.         Write-Verbose "Destination path not found. Creating directory: $DestinationPath"
  56.         New-Item -ItemType Directory -Force -Path $DestinationPath | Out-Null
  57.     }
  58.  
  59.     $zip = [System.IO.Compression.ZipFile]::OpenRead($ZipFilePath)
  60.     Write-Verbose "Successfully opened ZIP file: $ZipFilePath"
  61.  
  62.     $targetFolderPathInZip = $null
  63.  
  64.     if ($PSCmdlet.ParameterSetName -eq 'ByName') {
  65.         Write-Host "Searching for folder named '$FindFolderByName'..."
  66.         # Find directory entries (ending with /) and get the one that matches the name
  67.         $foundEntry = $zip.Entries | Where-Object {
  68.             $_.FullName.EndsWith('/') -and ($_.FullName.TrimEnd('/').Split('/')[-1] -eq $FindFolderByName)
  69.         } | Select-Object -First 1
  70.  
  71.         if ($foundEntry) {
  72.             $targetFolderPathInZip = $foundEntry.FullName.TrimEnd('/')
  73.             Write-Host "Found folder at: $targetFolderPathInZip"
  74.         } else {
  75.             Write-Warning "Could not find any folder named '$FindFolderByName' in the archive."
  76.             $zip.Dispose()
  77.             return
  78.         }
  79.     } else { # ByPath
  80.         $targetFolderPathInZip = $FolderPathInZip
  81.     }
  82.    
  83.     # Normalize the user-provided path to use forward slashes, which is what ZipFile entries use.
  84.     $normalizedFolderPath = $targetFolderPathInZip.Replace('\', '/')
  85.     # Append a slash to ensure we match a directory, not a file with a similar name.
  86.     $folderPathInZipForSearch = "$normalizedFolderPath/"
  87.  
  88.     $entries = $zip.Entries | Where-Object { $_.FullName.StartsWith($folderPathInZipForSearch, [System.StringComparison]::OrdinalIgnoreCase) }
  89.  
  90.     if ($entries.Count -eq 0) {
  91.         Write-Warning "No items found at path '$targetFolderPathInZip' in the ZIP archive."
  92.         $zip.Dispose()
  93.         return
  94.     }
  95.  
  96.     Write-Host "Found $($entries.Count) files and folders to extract from '$targetFolderPathInZip'."
  97.  
  98.     $parentPathInZip = [System.IO.Path]::GetDirectoryName($normalizedFolderPath).Replace('\', '/')
  99.  
  100.     foreach ($entry in $entries) {
  101.         $relativePath = $entry.FullName
  102.         if (-not [string]::IsNullOrEmpty($parentPathInZip)) {
  103.             $relativePath = $entry.FullName.Substring($parentPathInZip.Length + 1)
  104.         }
  105.  
  106.         $fullDestinationPath = Join-Path $DestinationPath $relativePath
  107.  
  108.         $directoryName = [System.IO.Path]::GetDirectoryName($fullDestinationPath)
  109.         if ($directoryName -and (-not (Test-Path $directoryName))) {
  110.             New-Item -ItemType Directory -Path $directoryName -Force | Out-Null
  111.         }
  112.  
  113.         if ($entry.Name -ne "") {
  114.             Write-Verbose "Extracting $($entry.FullName) to $fullDestinationPath"
  115.             [System.IO.Compression.ZipFileExtensions]::ExtractToFile($entry, $fullDestinationPath, $true)
  116.         }
  117.     }
  118.  
  119.     Write-Host "Extraction complete."
  120.     Write-Host "The folder '$targetFolderPathInZip' has been extracted to '$DestinationPath'"
  121. }
  122. catch {
  123.     Write-Error "An error occurred: $_"
  124. }
  125. finally {
  126.     if ($zip) {
  127.         $zip.Dispose()
  128.     }
  129. }
  130.  
  131. # --- Example Usage ---
  132. # To use this script:
  133. # 1. Save it as a .ps1 file (e.g., Extract-SpecificFolderFromZip.ps1).
  134. # 2. Open a PowerShell terminal and navigate to the directory where you saved the file.
  135. # 3. You may need to change your execution policy: Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
  136. # 4. Call the script with your parameters as shown in the examples above.
Advertisement
Add Comment
Please, Sign In to add comment