Function to format an IPv4 Address to MaskedTextBox format

Ask questions about creating Graphical User Interfaces (GUI) in PowerShell and using WinForms controls.
Forum rules
Do not post any licensing information in this forum.

Any code longer than three lines should be added as code using the 'Select Code' dropdown menu or attached as a file.
Locked
User avatar
jjangli
Posts: 1
Last visit: Thu Jun 12, 2014 3:02 am

Function to format an IPv4 Address to MaskedTextBox format

Post 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 '.')

}

Locked