I am trying to split all PDF files in a folder and then move them into an output folder. The trouble is, the program I am using (PDFtk) only split one file at a time.
This works great if there is only 1 file, but frequently users scan multiple files in at a time, and that causes the PowerShell script to shrug and just perform the move to output without splitting the files. Am I using ForEach
incorrectly?
$pdfPath = 'C:\Temp\Incoming'
$pdfoutPath = 'C:\Temp\Completed'
$pdfFile = Join-Path $pdfPath '*.pdf'
$SetsOfPages = 1
$Match = 'NumberOfPages: (\d+)'
$NumberOfPages = [regex]::Match((pdftk $pdfFile dump_data), $Match).Groups[1].Value
"{0,2} pages in {1}" -f $NumberOfPages, $pdfFile
Get-ChildItem $pdfFile | ForEach-Object {
for ($Page=1; $Page -le $NumberOfPages; $Page+=$SetsOfPages) {
$File = Get-Item $pdfFile
$Range = "{1}" -f $page, [Math]::Min($Page+$SetsOfPages-1, $NumberOfPages)
$OutFile = Join-Path $pdfoutPath ($File.BaseName + "_$Range.pdf")
"processing: {0}" -f $OutFile
pdftk $pdfFile cat $Range output $OutFile
}
Get-ChildItem $pdfoutPath '*.pdf' -Recurse | foreach {
$new_folder_Year = Get-Date $_.LastWriteTime -Format yyyy
$new_folder_Month = Get-Date $_.LastWriteTime -uformat %m
$new_folder_Day = Get-Date $_.LastWriteTime -uformat %d
$des_path = "${pdfoutPath}\${new_folder_Year}\${new_folder_Month}\${new_folder_Day}"
if (Test-Path $des_path){
Move-Item $_.FullName $des_path
} else {
New-Item -ItemType Directory -Path $des_path
Move-Item $_.FullName $des_path
}
}
Get-ChildItem $pdfPath '*.pdf' -Recurse | foreach {
$new_folder_Year = Get-Date $_.LastWriteTime -Format yyyy
$new_folder_Month = Get-Date $_.LastWriteTime -uformat %m
$new_folder_Day = Get-Date $_.LastWriteTime -uformat %d
$des_path = "${pdfoutPath}\${new_folder_Year}\${new_folder_Month}\${new_folder_Day}"
if (Test-Path $des_path){
Move-Item $_.FullName $des_path
} else {
New-Item -ItemType Directory -Path $des_path
Move-Item $_.FullName $des_path
}
}