Resolve-MacAddress.ps1


<#PSScriptInfo
 
.VERSION 1.16.2
 
.GUID 1d517baf-fecc-4167-8f93-4dbe965ac0fd
 
.AUTHOR saw-friendship
 
.COMPANYNAME
 
.COPYRIGHT saw-friendship
 
.TAGS
 saw-friendship Hardware Vendor MAC MacAddress LinkLayerAddress PhysicalAddress LookUp IEEE
 
.LICENSEURI
 
.PROJECTURI https://sawfriendship.wordpress.com/
 
.ICONURI
 
.EXTERNALMODULEDEPENDENCIES
 
.REQUIREDSCRIPTS
 
.EXTERNALSCRIPTDEPENDENCIES
 
.RELEASENOTES
 
#>


<#
 
.DESCRIPTION
 
 Get Hardware Vendor by MacAddress. Download Database from IEEE site
 
#>
 

[CmdletBinding()]
param(
    [Parameter(Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)][alias("LinkLayerAddress","PhysicalAddress")][string[]]$MAC,
    [switch]$PassThru,
    [switch]$UpdateFile
)

    if(!$PSScriptRoot){$PSScriptRoot = Split-Path $MyInvocation.MyCommand.Path -Parent}
    
    $MacVendorTableCSVpath = Join-Path -Path $PSScriptRoot -ChildPath "MacVendorTable.ieee.org.csv"
    $regexEscape = [regex]::Escape('(hex)')
    # $OuiTxtUrl = "http://www.ieee.org/netstorage/standards/oui.txt"
    $OuiTxtUrl = "http://standards-oui.ieee.org/oui.txt"
    if(!(Test-Path Variable:MacVendorTable)){
        $Global:MacVendorTable = @{}
    }
    if($UpdateFile -or (!(Test-Path $MacVendorTableCSVpath))){
        try{
            $ouitxt = Invoke-WebRequest -Uri $OuiTxtUrl -UseBasicParsing
            $oui = $ouitxt.Content -split "`n" | Select-String $regexEscape
        } catch {
            Write-Warning "file not exists"
            break
        }
        $oui | % {
            $MacAddr,$Vendor = $_ -split $regexEscape -replace "^\s+|\s+$"
            $MacAddr = $MacAddr -replace "\-"
            try{
                $MacVendorTable.Add($MacAddr,$Vendor)
            } catch{
            
            }
        }
        $MacVendorTable.GetEnumerator() | sort Name | % {
                [PsCustomObject][Ordered]@{
                    'Mac' = $_.Key
                    'Vendor' = $_.Value
                }
            } | Export-Csv -Delimiter ';' -NoTypeInformation -Path $MacVendorTableCSVpath
    } elseif((Test-Path $MacVendorTableCSVpath) -and ($MacVendorTable.count -eq 0)){
        $Global:MacVendorTable = @{}
        Import-Csv -Delimiter ';' -Path $MacVendorTableCSVpath | % {($Global:MacVendorTable).Add($_.Mac,$_.Vendor)}
    }else{}
    
    $MAC | % {
        $MAC6 = $_ -replace "[g-z]|[^\w\d]" -replace "([\w\d]{6})(.+)",'$1'
        if(($MAC6 -match "\d|\w") -and ($MAC6.Length -eq 6) -and ($MAC6 -ne '000000')){
            if(!$PassThru){
                $MacVendorTable[$MAC6]
            } else {
                [pscustomobject][Ordered]@{
                'MAC' = $_
                'Vendor' = $MacVendorTable[$MAC6]
                }
            }
        }
    }