Public/Get-MacAddressFromText.ps1
|
function Get-MacAddressFromText { <# .SYNOPSIS Find every MAC address in free-form text and look them all up. Requires an API key. .DESCRIPTION Calls POST /v1/mac/extract. Feed it the output of 'arp -a', a DHCP lease file, a switch config, a log dump, anything: it pulls out every MAC-shaped substring and resolves each one, same result shape as Resolve-MacAddress. The server caps the number of addresses per call; when it truncates, a warning is written. .PARAMETER Text The text to scan. Accepts pipeline input; multiple items are joined with newlines into one request. .PARAMETER Path Read the text from a file instead of -Text. .PARAMETER ApiKey API key. Falls back to Set-MacadressConfiguration, then the MACADRESS_API_KEY environment variable. .PARAMETER Raw Return the decoded API response verbatim (count, truncated, results). .EXAMPLE arp -a | Out-String | Get-MacAddressFromText | Select-Object input, organization .EXAMPLE Get-MacAddressFromText -Path .\dhcpd.leases .LINK https://macadress.com/docs .LINK https://github.com/sapisos/macadress-powershell #> [CmdletBinding(DefaultParameterSetName = 'Text')] [OutputType('Macadress.MacResult')] param( [Parameter(Mandatory, Position = 0, ValueFromPipeline, ParameterSetName = 'Text')] [string[]] $Text, [Parameter(Mandatory, ParameterSetName = 'Path')] [ValidateNotNullOrEmpty()] [string] $Path, [Parameter()] [string] $ApiKey, [Parameter()] [switch] $Raw ) begin { $null = Assert-MacadressApiKey -ApiKey $ApiKey -Operation 'Get-MacAddressFromText' $buffer = [System.Collections.Generic.List[string]]::new() } process { if ($PSCmdlet.ParameterSetName -eq 'Text') { foreach ($line in $Text) { $buffer.Add([string]$line) } } } end { if ($PSCmdlet.ParameterSetName -eq 'Path') { $resolved = Resolve-Path -LiteralPath $Path -ErrorAction Stop $content = Get-Content -LiteralPath $resolved -Raw } else { $content = $buffer -join "`n" } if ([string]::IsNullOrWhiteSpace($content)) { throw [System.Management.Automation.PSArgumentException]::new('No text to scan.') } try { $response = Invoke-MacadressApi -Method POST -Path 'v1/mac/extract' -Body @{ text = $content } -ApiKey $ApiKey } catch { Write-Error -ErrorRecord $_ return } if ($Raw) { return $response } if ($response.truncated) { Write-Warning "The text held more addresses than the server processes in one call; results are truncated." } foreach ($item in @($response.results)) { if ($item -is [psobject] -and -not $item.PSObject.TypeNames.Contains('Macadress.MacResult')) { $item.PSObject.TypeNames.Insert(0, 'Macadress.MacResult') } $item } } } |