Public/Add-SpecPrinterPort.ps1

function Add-SpecPrinterPort {
    <#
    .SYNOPSIS
    Adds a printer port for a specified printer IP.
 
    .DESCRIPTION
    The Add-SpecPrinterPort function attempts to add a printer port for a specified printer IP address. It provides verbose output for successful or unsuccessful port addition.
 
    .PARAMETER printerIP
    Specifies the IP address of the printer.
 
    .PARAMETER printerPort
    Specifies the name of the printer port to add.
 
    .EXAMPLE
    Add-SpecPrinterPort -printerIP "192.168.1.100" -printerPort "PortXYZ"
    Attempts to add the printer port "PortXYZ" for the printer with IP address "192.168.1.100".
 
    .OUTPUTS
    Returns an array of codes including if any errors occurred during the process. The following codes can be returned:
    700 - Printer port added successfully
    701 - The specified port already exists.
    702 - An unknown error occurred. (Check the error message for more information.)
 
    .NOTES
    Author: owen.heaume
    Version: 1.0
    #>


    [cmdletbinding()]
    param (
        [Parameter(Mandatory = $true)]
        [string]$printerIP,
        [Parameter(Mandatory = $true)]
        [string]$printerPort
    )

    try {
        write-verbose "Adding printer port $printerPort for IP $printerIP"
        Add-PrinterPort -name $printerPort -PrinterHostAddress $printerIP -ErrorAction Stop -ErrorVariable x
        Write-Verbose "Printer Port $printerPort added for IP $printerIP"
        return 700
    } catch {
        Write-Warning "Unable to add printer port $printerPort for IP $printerIP"
        if ($x-match "The specified port already exists.") {
            write-host "The specified port already exists." -ForegroundColor cyan
            return 701
        } else {
            write-warning "The error message was: $x"
             return 702
        }
    }
}