Jason
Jason

Reputation: 821

Extracting and printing the first 3 octets of a MAC using powershell

if($ping)
    {
        ( $mac | ? { $_ -match $ip } ) -match "([0-9A-F]{2}([:-][0-9A-F]{2}){5})" | out-null;
        if ( $matches ) {
            Select-String -Pattern '[0-9A-F]{2}-[0-9A-F]{2}-[0-9A-F]{2}' -Path $matches[0] |
            ForEach-Object {$_.Matches[0].Value}
        } else {
            "Not Found"
        }
    }

Is what I am currently using. Not sure if I am doing this right in PowerShell.

I am trying to Extract the first 3 XX:XX:XX of a MAC so that I can use it for a compare. I'm just not sure how pull after the match.

Upvotes: 2

Views: 405

Answers (1)

Martin Brandl
Martin Brandl

Reputation: 59001

You can use Remove to crop the first 8 characters:

$mac ='00:0a:95:9d:68:16' 

$mac.Remove(8, ($mac.Length -8))

Output:

00:0a:95

You can also do it using a regex:

[regex]::Match($mac, '^(.{8})').Groups[1].Value

Upvotes: 2

Related Questions