PoshCode Logo PowerShell Code Repository

Name: 680581.ps1

Goes one directory deep into the $RootPath and then recurses through the subdirectories for any zip files, extracting the PDFs inside to a common location.

  1. Param(
  2.     [Parameter(Mandatory=$true)][string]$RootPath,
  3.     [Parameter(Mandatory=$true)][string]$Destination,
  4.     [Parameter(Mandatory=$true)][string]$LogPath
  5. )
  6.  
  7. function Expand-ZipFile {
  8.     Param(
  9.         [Parameter(Mandatory=$true)][string]$File,
  10.         [Parameter(Mandatory=$true)][string]$Path
  11.     )
  12.     [System.Reflection.Assembly]::LoadWithPartialName("System.IO.Compression.FileSystem") | Out-Null
  13.     [System.IO.Compression.ZipFile]::ExtractToDirectory($File, $Path)
  14. }
  15.  
  16. function Write-Log {
  17.     Param(
  18.     [Parameter(Mandatory=$true, Position=1)][alias("P")][string]$Path,
  19.     [Parameter(Mandatory=$true, Position=2)][alias("V")][string]$Value,
  20.     [alias("D")][Switch]$AddDateTime,
  21.     [alias("L")][Switch]$LogOnly
  22.     )
  23.     if($AddDateTime) {
  24.         $Value = "$(Get-Date -Format MMddyyyy-hh:mm:ss) - $Value"
  25.     }
  26.     if(!$LogOnly) {
  27.         Write-Host $Value
  28.     }
  29.     Add-Content -Path $Path -Value $Value
  30. }
  31.  
  32. $subFolders = gci -Path $RootPath -Directory
  33. foreach($subFolder in $subFolders) {
  34.     $zipFiles = gci -Path $subFolder.FullName -Recurse -Include "*.zip" -File
  35.     foreach($zipFile in $zipFiles) {
  36.         $zipFilePath = $zipFile.FullName
  37.         $pdfPath = ""
  38.         if($Destination.EndsWith("\")) {
  39.             $pdfPath = "$Destination$($zipFile.BaseName).pdf"
  40.         }
  41.         else {
  42.             $pdfPath = "$Destination\$($zipFile.BaseName).pdf"
  43.         }
  44.        
  45.         Write-Host "Extracting $zipFilePath"
  46.         if(-Not (Test-Path -Path $pdfPath)) {
  47.             try {
  48.                 Expand-ZipFile -File $zipFilePath -Path $Destination
  49.             }
  50.             catch {
  51.                 Write-Log -Path $LogPath -Value "$($zipFile.FullName) failed to extract."
  52.             }
  53.         }
  54.         else {
  55.             Write-Host "$pdfPath exists."
  56.         }
  57.     }
  58. }

Submit a correction or amendment below (
click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:


Remember me