diff --git a/RenameInvoice.ps1 b/RenameInvoice.ps1 index b420e51..73b9928 100644 --- a/RenameInvoice.ps1 +++ b/RenameInvoice.ps1 @@ -1,4 +1,4 @@ -# Ensure 'pdftotext.exe' is available in your PATH or specify full path here +# Ensure 'pdftotext.exe' is available in your PATH or specify the full path here $pdftotextPath = "pdftotext.exe" # Get all PDF files in the script's current directory @@ -17,13 +17,12 @@ foreach ($pdfFile in $pdfFiles) { # Initialize Bill To name $billToName = $null - # Improved search for the line containing 'Bill to' (allowing whitespace variations) + # More robust method: look for "Bill to" line and grab the next meaningful line for ($i = 0; $i -lt $lines.Length; $i++) { - if ($lines[$i] -match '^\s*Bill\s+to\s*$') { - # Next non-empty line is the name + if ($lines[$i].Trim() -match '^Bill\s+to$') { for ($j = $i + 1; $j -lt $lines.Length; $j++) { $nextLine = $lines[$j].Trim() - if ($nextLine -ne "") { + if (![string]::IsNullOrWhiteSpace($nextLine)) { $billToName = $nextLine break } @@ -33,10 +32,10 @@ foreach ($pdfFile in $pdfFiles) { } if ($billToName) { - # Clean up name (remove invalid filename chars) + # Clean name from invalid filename characters $cleanName = ($billToName -replace '[\\/:*?"<>|]', '').Trim() - # Construct new filename safely + # Construct safe filename $newFileName = "$cleanName 2025 calendar ad invoice.pdf" $destPath = Join-Path -Path $pdfFile.DirectoryName -ChildPath $newFileName