nameInvoices.ps1

<#
.SYNOPSIS
Names invoices in a given folder according to their metadata.
 
.DESCRIPTION
Sents all files to billomat as inbox documents for categorization and uses the returned metadata to create
uniform filenames
 
.PARAMETER path
    Folder to name documents in.
 
.EXAMPLE
    Names documents in the given folder.
     
    .\nameInvoices.ps1 -path c:\invoices
#>

[CmdletBinding(SupportsShouldProcess=$true)]
param(
    [ValidateScript({
        if(-Not ($_ | Test-Path -PathType Container) ){
            throw "Path '$_' does not exist."
        }
        return $true
    })]
    [System.IO.FileInfo] $path
)

# check prerequisites
$bmtModule = Get-Module -ListAvailable -Name "Billomat";
if (!$bmtModule) { throw "Module 'Billomat' needed. Please install executing 'Install-Module -Name Billomat' as Administrator."; }
Write-Information "Using Billomat Module v$($bmtModule.Version)."

$files = Get-ChildItem $path -Recurse | Where-Object { !$_.PSIsContainer};
foreach ($file in $files) {
    Write-Output "Processing file $($file.FullName)...";

    $inboxDocId = Get-Content -Path $file.FullName -Encoding Byte -Raw | Add-BMTInboxDoc;

    try {
        $metaData = @{};
        Start-Sleep -s 10;
        for($i = 0;$i -lt 5;$i++) {
            $metaData = Read-BMTInboxDoc $inboxDocId;
            if($metaData.Count -gt 0) {
                $newName = "x $($metaData["DATE"]) $($metaData["paymentRecipient"] -replace "[ ]", "_")_$($metaData["INVOICE_NUMBER"])$($file.Extension)"; 
                Write-Output "Renaming '$file' to '$newName'...";
                Rename-Item -Path $file.FullName -NewName $newName;
                break;
            } else {
                Write-Output "Metadata not processed so far for '$file', will retry in 3 seconds...";
            }
            Start-Sleep -s 3;
        }
    } finally {
        Remove-BMTInboxDoc $inboxDocId;
    }
}