Page 1 of 1

Function to format an IPv4 Address to MaskedTextBox format

Posted: Tue Oct 29, 2013 7:34 am
by jjangli
Hi!

In my GUI I use a MaskedTextBox for IPv4 addresses, with mask: 990.990.990.990

The function below can help you to 'align' an IP address into a MaskedTextbox.

I would like to share this little function with you all.
Enjoy.

PowerShell Code
Double-click the code block to select all.
Function Format-IpV4AddressMaskedTextBox {
<#
    .SYNOPSIS
        Formats an IPv4 text string for a MaskedTextBox.

    .OUTPUTS
        String.
        A MaskedTextBox-formatted IpV4 text.

    .EXAMPLE
        PS C:\> Write-Host (WsApp-Format-IpV4Address -IpV4Address '10.230.12.5' -FillCharacter '_')
        PS C:\> _10.230._12.__5

        PS C:\> Write-Host (WsApp-Format-IpV4Address -IpV4Address '1.1.1.1'     -FillCharacter '0')
        PS C:\> 001.001.001.001
#>

    Param(
        [String]$IpV4Address,
        [Char]$FillCharacter = ' '
    )

    # Return untouched.
    If ([String]::IsNullOrWhiteSpace($IpV4Address)) { Return $IpV4Address }
       
    [Array]$Private:newIp = @()
    
    # Split the IP address and add leading spaces.
    ForEach ($Private:number In ($IpV4Address -split [RegEx]::Escape('.'))) {
        $newIp += $number.PadLeft(3, $FillCharacter)
    }
    
    Return ($newIp -join '.')

}