PSZebraSGD.psm1

function Invoke-ZebraTcpCommand {
    <#
    .SYNOPSIS
        Sends one command over a new TCP connection.
    .DESCRIPTION
        Encodes the command as ASCII with a trailing CRLF. Unless NoResponse is set,
        waits for the first read and continues only while more bytes are immediately available.
        Decodes the received bytes as UTF-8 and trims leading and trailing whitespace.
    .PARAMETER ComputerName
        Printer hostname or IP address.
    .PARAMETER Command
        Command text without its terminating CRLF.
    .PARAMETER Port
        TCP port from 1 through 65535. Defaults to 9100.
    .PARAMETER TimeoutMilliseconds
        Connect, send and receive timeout in milliseconds, from 100 through 60000. Defaults to 3000.
    .PARAMETER MaxResponseBytes
        Largest accepted reply in bytes, from 1 through 1048576. Defaults to 65536.
        Reading more than this limit raises an error.
    .PARAMETER NoResponse
        Returns after the write without reading a reply or confirming acceptance.
    .EXAMPLE
        Invoke-ZebraTcpCommand -ComputerName 192.0.2.10 -Command '! U1 getvar "device.unique_id"'
    .INPUTS
        None.
    .OUTPUTS
        System.String. Returns the trimmed reply unless NoResponse is set, in which case there is no output.
    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [string]$ComputerName,

        [Parameter(Mandatory)]
        [string]$Command,

        [ValidateRange(1, 65535)]
        [int]$Port = 9100,

        [ValidateRange(100, 60000)]
        [int]$TimeoutMilliseconds = 3000,

        [ValidateRange(1, 1048576)]
        [int]$MaxResponseBytes = 65536,

        [switch]$NoResponse
    )

    $Client = [System.Net.Sockets.TcpClient]::new()

    try {
        $ConnectTask = $Client.ConnectAsync($ComputerName, $Port)
        if (-not $ConnectTask.Wait($TimeoutMilliseconds)) {
            throw "Connection timed out: ${ComputerName}:$Port"
        }

        $Client.SendTimeout = $TimeoutMilliseconds
        $Client.ReceiveTimeout = $TimeoutMilliseconds
        $Stream = $Client.GetStream()
        $Payload = [System.Text.Encoding]::ASCII.GetBytes($Command + "`r`n")
        $Stream.Write($Payload, 0, $Payload.Length)

        if ($NoResponse) {
            return
        }

        $Buffer = [byte[]]::new(4096)
        $Response = [System.IO.MemoryStream]::new()

        try {
            $BytesRead = $Stream.Read($Buffer, 0, $Buffer.Length)

            while ($BytesRead -gt 0) {

                if ($Response.Length + $BytesRead -gt $MaxResponseBytes) {
                    throw 'Response exceeds MaxResponseBytes.'
                }
                $Response.Write($Buffer, 0, $BytesRead)

                if (-not $Stream.DataAvailable) {
                    break
                }
                $BytesRead = $Stream.Read($Buffer, 0, $Buffer.Length)
            }
            return [System.Text.Encoding]::UTF8.GetString($Response.ToArray()).Trim()
        } finally {
            $Response.Dispose()
        }
    } finally {
        $Client.Dispose()
    }
}

function Get-ZebraConfiguration {
    <#
    .SYNOPSIS
        Reads named SGD settings from a Zebra printer.
    .DESCRIPTION
        Queries each name in the supplied order. Repeated names are queried again.
    .PARAMETER ComputerName
        Printer hostname or IP address.
    .PARAMETER Name
        One or more SGD variable names.
    .PARAMETER Port
        Printer TCP port. Defaults to 9100.
    .EXAMPLE
        Get-ZebraConfiguration -ComputerName 192.0.2.10 -Name device.unique_id, appl.name
    .INPUTS
        None.
    .OUTPUTS
        System.Management.Automation.PSCustomObject. Each record has ComputerName, Name and Value properties.
    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [string]$ComputerName,

        [Parameter(Mandatory)]
        [string[]]$Name,

        [int]$Port = 9100
    )

    foreach ($SettingName in $Name) {
        $ReadParameters = @{
            ComputerName = $ComputerName
            Operation    = 'Get'
            Name         = $SettingName
            Port         = $Port
        }

        [PSCustomObject]@{
            ComputerName = $ComputerName
            Name         = $SettingName
            Value        = Invoke-ZebraSGD @ReadParameters
        }
    }
}

function Get-ZebraPrinter {
    <#
    .SYNOPSIS
        Reads identification and firmware information from a Zebra printer.
    .DESCRIPTION
        Queries four SGD variables in sequence. If a query throws, the command warns,
        leaves that property null and continues with the remaining variables.
    .PARAMETER ComputerName
        Printer hostname or IP address.
    .PARAMETER Port
        Printer TCP port. Defaults to 9100.
    .EXAMPLE
        Get-ZebraPrinter -ComputerName 192.0.2.10
    .INPUTS
        None.
    .OUTPUTS
        System.Management.Automation.PSCustomObject. Contains ComputerName, UniqueId, FriendlyName,
        Application and Firmware.
    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [string]$ComputerName,

        [int]$Port = 9100
    )

    $Fields = @('device.product_name', 'device.unique_id', 'device.friendly_name', 'appl.name', 'appl.link_os_version', 'ip.active_network', 'interface.network.active.mac_addr','odometer.total_label_count')

    $Values = @{}
    foreach ($Field in $Fields) {
        $ReadParameters = @{
            ComputerName = $ComputerName
            Operation    = 'Get'
            Name         = $Field
            Port         = $Port
        }
        try {
            $Values[$Field] = Invoke-ZebraSGD @ReadParameters
        } catch {
            Write-Warning "${Field}: $_"
            $Values[$Field] = $null
        }
    }

    [PSCustomObject]@{
        ComputerName  = $ComputerName
        ProductName   = $Values['device.product_name']
        UniqueId      = $Values['device.unique_id']
        FriendlyName  = $Values['device.friendly_name']
        Application   = $Values['appl.name']
        Firmware      = $Values['appl.link_os_version']
        ActiveNetwork = $Values['ip.active_network']
        MacAddr       = $Values['interface.network.active.mac_addr']
        LabelsPrinted = $Values['odometer.total_label_count']
    }
}

function Invoke-ZebraSGD {
    <#
    .SYNOPSIS
        Sends a Get, Set or Do SGD command to a Zebra printer.
    .DESCRIPTION
        Get reads the reply, even under WhatIf. Set and Do support confirmation and WhatIf.
        Neither waits for a reply or verifies printer acceptance.
    .PARAMETER ComputerName
        Printer hostname or IP address.
    .PARAMETER Operation
        Get reads a variable, Set writes a variable and Do requests an action.
    .PARAMETER Name
        SGD variable or action name, such as device.friendly_name.
    .PARAMETER Value
        Argument for Set or Do. Defaults to an empty string. Double quotes, carriage returns and
        line feeds are rejected for all operations, even though Get does not send a value.
    .PARAMETER Port
        Printer TCP port. Defaults to 9100.
    .PARAMETER TimeoutMilliseconds
        Timeout for connecting and for individual socket operations. Defaults to 3000 milliseconds.
    .EXAMPLE
        Invoke-ZebraSGD -ComputerName 192.0.2.10 -Operation Get -Name device.friendly_name
    .INPUTS
        None.
    .OUTPUTS
        System.String. Get returns the trimmed reply. Set and Do return no output.
    #>

    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')]
    param(
        [Parameter(Mandatory)]
        [string]$ComputerName,

        [Parameter(Mandatory)]
        [ValidateSet('Get', 'Set', 'Do')]
        [string]$Operation,

        [Parameter(Mandatory)]
        [ValidatePattern('^[a-zA-Z][a-zA-Z0-9_.-]*$')]
        [string]$Name,

        [string]$Value = '',

        [int]$Port = 9100,

        [int]$TimeoutMilliseconds = 3000
    )

    if ($Value.Contains('"') -or $Value.Contains("`r") -or $Value.Contains("`n")) {
        throw 'Value contains unsupported quote or newline characters.'
    }

    $Command = switch ($Operation) {
        'Get' {
            '! U1 getvar "{0}"' -f $Name
        }
        'Set' {
            '! U1 setvar "{0}" "{1}"' -f $Name, $Value
        }
        'Do' {
            '! U1 do "{0}" "{1}"' -f $Name, $Value
        }
    }

    $TcpParameters = @{
        ComputerName        = $ComputerName
        Command             = $Command
        Port                = $Port
        TimeoutMilliseconds = $TimeoutMilliseconds
    }

    if ($Operation -eq 'Get') {
        return Invoke-ZebraTcpCommand @TcpParameters
    }

    if ($PSCmdlet.ShouldProcess($ComputerName, "$Operation SGD $Name")) {
        Invoke-ZebraTcpCommand @TcpParameters -NoResponse
    }
}

function Set-ZebraConfiguration {
    <#
    .SYNOPSIS
        Writes one SGD setting to a Zebra printer.
    .DESCRIPTION
        Sends a setvar command after confirmation without waiting for a reply.
        A successful write does not confirm that the printer accepted the value.
    .PARAMETER ComputerName
        Printer hostname or IP address.
    .PARAMETER Name
        SGD variable to set.
    .PARAMETER Value
        Setting value. Double quotes, carriage returns and line feeds are unsupported.
    .PARAMETER Port
        Printer TCP port. Defaults to 9100.
    .EXAMPLE
        Set-ZebraConfiguration -ComputerName 192.0.2.10 -Name device.friendly_name -Value 'West Desk' -WhatIf
    .INPUTS
        None.
    .OUTPUTS
        None.
    #>

    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')]
    param(
        [Parameter(Mandatory)]
        [string]$ComputerName,

        [Parameter(Mandatory)]
        [string]$Name,

        [Parameter(Mandatory)]
        [string]$Value,

        [int]$Port = 9100
    )

    if ($PSCmdlet.ShouldProcess($ComputerName, "Set SGD $Name")) {
        $SetParameters = @{
            ComputerName = $ComputerName
            Operation    = 'Set'
            Name         = $Name
            Value        = $Value
            Port         = $Port
            Confirm      = $false
        }

        Invoke-ZebraSGD @SetParameters
    }
}