Public/Set-specUSBPrinters.ps1

Function Set-specUSBPrinters {
    [cmdletBinding()]

    param (
        [Parameter()]
        [System.Object[]]$usbAssignedPrinters,

        [Parameter()]
        [System.Object[]]$printerModelTblData,

        [Parameter()]
        [System.Object[]]$usbLocalPrinters
    )

    #region 3.USB Printer processing
    if ((Get-specNumberOfItems $usbAssignedPrinters) -gt 0) {
        Write-Host 'Configuring USB printers' -ForegroundColor DarkCyan
        Write-Host '------------------------' -ForegroundColor DarkCyan
    }

    foreach ($usbPrtr in $usbAssignedPrinters) {
        # Extract the printer model and model number from the Printer_Name.
        # Assumes Printer_Name follows the format: <Manufacturer>_<Model>_<OptionalDetails>
        $model = ($usbPrtr.Printer_Name.Split('_')[0, 1]) -join ('_')
        $modelNo = ($usbPrtr.Printer_Name.Split('_')[1])

        # Get the printer model details
        $printerModelIndex = $printerModelTblData | Where-Object { $_.Printer_Type -eq $model }

        # Check if the printer exists locally (using $usbLocalPrinters)
        $printerExists = $usbLocalPrinters | ? { $_.Name -eq $usbPrtr.printer_name }

        if (!$printerExists) {
            Write-Host "USB printer $($usbPrtr.printer_name) not found locally. Checking for a matching local USB port driver '$($printerModelIndex.Printer_DriverName)' against the Azure table data..." -ForegroundColor DarkGray

            # Find a matching USB port
            foreach ($localPrinter in $usbLocalPrinters) {
                if ($localPrinter.DriverName -eq $printerModelIndex.Printer_DriverName) {
                    Write-Host "Matching port name $($localPrinter.PortName) for $($usbPrtr.printer_name)" -ForegroundColor Green
                    $printerPORT = $localPrinter.PortName
                    # Add the printer here
                    # Instantiate the Printer object using New-specPrinterObject
                    $printer = New-specPrinterObject -Name $usbPrtr.printer_name -Driver $printerModelIndex.Printer_DriverName -PortName $printerPORT
                    $printer.AddPrinter()

                    break
                } else {
                    if ($localPrinter.Name -notmatch $modelNo) {
                        Write-Host "Printer model $modelNo NOT matching $($localPrinter.Name) as driver is $($printerModelIndex.Printer_DriverName)" -ForegroundColor DarkYellow
                    }
                }
            }

            # Check if a port was assigned
            if (!$printerPORT) {
                Write-Host 'No matching local USB port found. Please check printer connections and driver installation.' -ForegroundColor Yellow
            }
            Write-Host
        }
    }
    #endregion 3.USB Printer processing
}