Skip to content

PowerShell Function: Fix-MAC

<#
.Synopsis
   Fixes various MAC address formats
.DESCRIPTION
   Takes an array of MAC addresses, tries to parse them, and outputs in a standard format
   Acceptable inputs include:
      aabbccddeeff
      "aa bb cc dd ee ff"
      aabb.ccdd.eeff
      aa-bb-cc-dd-ee-ff
      aa:bb:cc:dd:ee:ff
   
   Default Output: AA:BB:CC:DD:EE:FF
   -IOS Output   : aabb.ccdd.eeff
   -Lower Output : aa:bb:cc:dd:ee:ff
.EXAMPLE
   Fix-MAC aabb.ccdd.eeff
      AA:BB:CC:DD:EE:FF
.EXAMPLE
   Fix-MAC AABBCCDDEEFF -Lower
      aa:bb:cc:dd:ee:ff
.EXAMPLE
   Fix-MAC AA:BB:CC:DD:EE:FF -IOS
      aabb.ccdd.eeff
.EXAMPLE
   Get-Content c:\temp\macs.txt | Fix-MAC
      AA:BB:CC:DD:EE:FF
      FF:EE:DD:CC:BB:AA
      11:22:33:44:55:66
#>
function Fix-MAC
{
    [CmdletBinding(DefaultParameterSetName=’Upper’)]
    [OutputType([string])]
    Param
    (
        # MAC Address
        [Parameter(Mandatory=$true, 
                   ValueFromPipeline=$true,
                   ValueFromPipelineByPropertyName=$true, 
                   ValueFromRemainingArguments=$false, 
                   Position=0)]
        [Parameter(ParameterSetName='Upper')]
        [Parameter(ParameterSetName='Lower')]
        [Parameter(ParameterSetName='IOS')]
        [string[]]$MACS,
        
        [Parameter(Mandatory=$False,
                   ParameterSetName=’Lower’)]
        [switch]$Lower,
        
        [Parameter(Mandatory=$False,
        ParameterSetName=’IOS’)]
        [switch]$IOS
    )
    Process
    {
        foreach ($MAC in $MACS)
        {
            if ($MAC -match "^([a-f0-9]{2})[.\-: ]?([a-f0-9]{2})[.\-: ]?([a-f0-9]{2})[.\-: ]?([a-f0-9]{2})[.\-: ]?([a-f0-9]{2})[.\-: ]?([a-f0-9]{2})$")
            {
                if ($IOS)
                {
                    ("{0}{1}.{2}{3}.{4}{5}" -f $matches[1..6]).ToLower()
                }
                elseif ($Lower)
                {
                    ("{0}:{1}:{2}:{3}:{4}:{5}" -f $matches[1..6]).ToLower()
                }
                else
                {
                    ("{0}:{1}:{2}:{3}:{4}:{5}" -f $matches[1..6]).ToUpper()
                }
            }
            else
            {
                "Could not parse $MAC"
            }
        }
    }
}
Published inTech

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *