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"
|
$pdftotextPath = "pdftotext.exe"
|
||||||
|
|
||||||
# Get all PDF files in the script's current directory
|
# Get all PDF files in the script's current directory
|
||||||
@ -17,13 +17,12 @@ foreach ($pdfFile in $pdfFiles) {
|
|||||||
# Initialize Bill To name
|
# Initialize Bill To name
|
||||||
$billToName = $null
|
$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++) {
|
for ($i = 0; $i -lt $lines.Length; $i++) {
|
||||||
if ($lines[$i] -match '^\s*Bill\s+to\s*$') {
|
if ($lines[$i].Trim() -match '^Bill\s+to$') {
|
||||||
# Next non-empty line is the name
|
|
||||||
for ($j = $i + 1; $j -lt $lines.Length; $j++) {
|
for ($j = $i + 1; $j -lt $lines.Length; $j++) {
|
||||||
$nextLine = $lines[$j].Trim()
|
$nextLine = $lines[$j].Trim()
|
||||||
if ($nextLine -ne "") {
|
if (![string]::IsNullOrWhiteSpace($nextLine)) {
|
||||||
$billToName = $nextLine
|
$billToName = $nextLine
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
@ -33,10 +32,10 @@ foreach ($pdfFile in $pdfFiles) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if ($billToName) {
|
if ($billToName) {
|
||||||
# Clean up name (remove invalid filename chars)
|
# Clean name from invalid filename characters
|
||||||
$cleanName = ($billToName -replace '[\\/:*?"<>|]', '').Trim()
|
$cleanName = ($billToName -replace '[\\/:*?"<>|]', '').Trim()
|
||||||
|
|
||||||
# Construct new filename safely
|
# Construct safe filename
|
||||||
$newFileName = "$cleanName 2025 calendar ad invoice.pdf"
|
$newFileName = "$cleanName 2025 calendar ad invoice.pdf"
|
||||||
$destPath = Join-Path -Path $pdfFile.DirectoryName -ChildPath $newFileName
|
$destPath = Join-Path -Path $pdfFile.DirectoryName -ChildPath $newFileName
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user