Adding Line Numbers to Native Command Output

One of the great things about Powershell is that you can use all your standard command line tools, such as ipconfig and net.exe. The only issue is that these tools output text and Powershell works with objects. The output of commands such as ipconfig is actually an array.
PS 24 >  (ipconfig).GetType().BaseType.FullName
System.Array
Each item in that array is a string
PS 31 >  (ipconfig)[4].gettype().FullName
System.String
So really you end up with an array of strings and if you know the indexes of that array, you can work with much more specific data. For example:
PS 58 >  (ipconfig)[7]
   IPv4 Address. . . . . . . . . . . : 10.2.4.48
But how do you know that this is line 7, or the 7th item in the array. You can run the command and count lines and guess, or you can do something like this:

PS 57 >  $i = 0;ipconfig| % {$i++;"$($i-1) `t $_"}
0
1        Windows IP Configuration
2
3
4        Ethernet adapter Local Area Connection:
5
6           Connection-specific DNS Suffix  . : corp.example.com
7           IPv4 Address. . . . . . . . . . . : 10.2.4.48
8           Subnet Mask . . . . . . . . . . . : 255.255.254.0
9           Default Gateway . . . . . . . . . : 10.2.4.1
10
11       Tunnel adapter Local Area Connection* 6:
12
13          Media State . . . . . . . . . . . : Media disconnected
14          Connection-specific DNS Suffix  . :
15
16       Tunnel adapter Local Area Connection* 7:
17
18          Media State . . . . . . . . . . . : Media disconnected
19          Connection-specific DNS Suffix  . : corp.example.com
Now you can know for sure what line you need to access and work with.

(ipconfig)[19] will give me my DNS name.

The other way around this is working with regular expressions to parse the file, but this will get you something really quickly. It works for a bunch of commands as well.

If you are really up for "objectifying" text output, check out Lee Holme's Awk with a Vengeance

Andy
    
Comments are closed