At a previous company I worked at, we managed over 60+ sites, each with a dedicated /24 subnet and a preconfigured printer on a print server. The challenge was to automatically add the local printer and move printers from other sites when users traveled between sites. Initially, I used a heavily modified VBS script from a friend to address this issue. Although this solution worked, it was slow over 300 lines long.

Unsatisfied with leaving behind a slow and cumbersome script, I recently rewrote it in PowerShell with some scripting help from ChatGPT. The new version is more efficient and significantly smaller. Below is the improved script.

#Remove printers
Get-Printer -Name "*PREFIX*" | Remove-Printer
 
# Get the IPv4 address of the active Ethernet or Wi-Fi network adapter that received its IP from DHCP
$ipAddress = Get-NetIPAddress -AddressFamily IPv4 | Where-Object { $_.InterfaceAlias -match 'Ethernet|Wi-Fi' -and $_.PrefixOrigin -eq 'Dhcp' } | Select-Object -First 1 -ExpandProperty IPAddress
 
if ($ipAddress) {
    Write-Output "Your DHCP-assigned IP Address is: $ipAddress"
    # Split the IP address into its octets
    $octets = $ipAddress -split '\.'
    # Extract the third octet
    $thirdOctet = $octets[2]
    # Dynamically construct the printer name
    $printerName = "PREFIX-$thirdOctet"
    # Construct the connection name
    $connectionName = "\\PRINTSERVER\" + $printerName
    Write-Output "Attempting to add printer: $connectionName"
    Add-Printer -ConnectionName $connectionName
} else {
    Write-Output "IP Address could not be found."
    }