2016/08/29

PowerShell Tip - Generate a list of Mac Addresses

While playing in my lab I needed to create a bunch of fake Devices in System Center Configuration Manager (SCCM). When creation devices you need two pieces of information, the computer name and the Mac Address of the device.

I used the following method to generate my list of mac addresses.

# First, get a list of mac address.
1..150 | ForEach-Object { '{0:X12}' -f $_ }
# Second step: Before we import we need to add a colon ":" every two characters
1..150|%{((('{0:X12}' -f $_) -split '(..)')|?{$_}) -join ":"}


What is happening here

  1. We list from the number 1 to 150
    1. 1..150
  2. We send each number to the pipeline and use composite formatting to convert the number to an hexadecimal that must me 12 characters. It will add leading zeros in this case.
    1. '{0:X12}' -f $_
  3. We then split every two characters using regex
    1. -split '(..)'
  4. We send this output to Where-Object to make sure we have a value. Our split is generating some empty values. We can double check that using those examples:
    1. ("000000000000" -split "(..)").count # returns 13
      ("000000000000" -split "(..)" | where { $_ }).count #returns 6
  5. Finally we join the whole string (that is currently splitted every two characters) using -join with the delimiter ":"
    1. -join ":"

Extra: Here is a list of fake ComputerName with their fake Mac Addresses


1..10 | ForEach-Object{
    # ComputerName
    $CompNumber = "TestFakeDevice{0:0000}" -f $_
    
    # Mac Address
    $CompMac = (('{0:X12}' -f $_) -split '(..)' | Where-Object { $_ }) -join '-'
    
    # Output information
    New-Object -TypeName PSObject -Property @{
        ComputerNumber = $CompNumber
        ComputerMacAddress = $CompMac
    }
}


Output:
ComputerNumber     ComputerMacAddress
--------------     ------------------
TestFakeDevice0001 00-00-00-00-00-00
TestFakeDevice0002 00-00-00-00-00-01
TestFakeDevice0003 00-00-00-00-00-02
TestFakeDevice0004 00-00-00-00-00-03
TestFakeDevice0005 00-00-00-00-00-04
TestFakeDevice0006 00-00-00-00-00-05
TestFakeDevice0007 00-00-00-00-00-06
TestFakeDevice0008 00-00-00-00-00-07
TestFakeDevice0009 00-00-00-00-00-08
TestFakeDevice0010 00-00-00-00-00-09


Thanks for reading! If you have any questions, leave a comment or send me an email at fxcat@lazywinadmin.com. I invite you to follow me on Twitter @lazywinadm / Google+ / LinkedIn. You can also follow the LazyWinAdmin Blog on Facebook Page and Google+ Page.

No comments:

Post a Comment