Update RenameInvoice.ps1
Trying direct line-match to clearly identifies the exact line that reads "Bill to" to avoid false matches. Next non-empty line: Reliably grabs the immediate next line with actual content as the customer's name. Filename safety: Removes characters Windows doesn't allow in filenames. Error and file existence handling: Provides informative messages if conflicts or errors occur.
This commit is contained in:
parent
d03498d118
commit
a633cc1f97
@ -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
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user