Solving Problems with PowerShell (Part 3)

by Apr 7, 2023

PowerShell offers you a plentitude of approaches to solve a task. They always boil down to the same strategies. In this mini-series, we will illustrate them all one by one.

Here’s the problem to solve: get the MAC address of your computer.

In our previous tips we looked at commands that would directly solve the puzzle. On Windows, you also have the rich information provided by the universal WMI service.

But what if all fails, and you cannot directly access the information?

Then it’s time for your next box of wizardry: operators and text operation. If you cannot get structured data, then maybe you can retrieve the information from more generic and unstructured data.

Here are two operators that extract the MAC address from text information emitted by ipconfig.exe:

The -like operator uses simple wildcard matching. While it is easy to use, its patterns are not very specific. That’s why it is sometimes hard to precisely select the information you are after.

 
PS C:\> (ipconfig /all) -like '*-*-*-*-*'
Physical Address. . . . . . . . . : 00-15-5D-58-46-A8
DHCPv6 Client DUID. . . . . . . . : 00-01-00-01-29-48-CB-2B-80-3F-5D-05-58-91
Physical Address. . . . . . . . . : 80-3F-5D-05-58-91
DHCPv6 Client DUID. . . . . . . . : 00-01-00-01-29-48-CB-2B-80-3F-5D-05-58-91
Physical Address. . . . . . . . . : 24-EE-9A-54-1B-E6
Physical Address. . . . . . . . . : 26-EE-9A-54-1B-E5
Physical Address. . . . . . . . . : 24-EE-9A-54-1B-E5
Physical Address. . . . . . . . . : 24-EE-9A-54-1B-E9 
 

The -match operator uses regular expressions. Designing patterns with regular expression to some feels like witch craft but fortunately it is easy to google for regex patterns. Regular expressions, when done right, are extremely precise and pick exactly what you need:

 
PS C:\> (ipconfig /all) -match '\s([0-9A-F]{2}-){5}[0-9A-F]{2}$'
   Physical Address. . . . . . . . . : 00-15-5D-58-46-A8
   Physical Address. . . . . . . . . : 80-3F-5D-05-58-91
   Physical Address. . . . . . . . . : 24-EE-9A-54-1B-E6
   Physical Address. . . . . . . . . : 26-EE-9A-54-1B-E5
   Physical Address. . . . . . . . . : 24-EE-9A-54-1B-E5
   Physical Address. . . . . . . . . : 24-EE-9A-54-1B-E9
 

The takeaway for today:

  • If there is no command delivering the information directly, and there is no command delivering structured information that contains what you need, then you can use operators to extract information from unstructured text


Tweet this Tip! Tweet this Tip!