How can I format a string in a pipeline?

rated by 0 users
This post has 2 Replies | 3 Followers

Not Ranked
Posts 1
ssg31415926 Posted: 05-16-2012 8:45 AM

I want to get a sorted, formatted list of MAC Addresses from Hyper-V.  So far, I've got:

get-vmnic | select Address | sort Address

which produces something like this:

Address
-------
00155D649A01
00155D649A02
00155D649A03
00155D649A05

but what I'd like is this:

Address
-------
00-15-5D-64-9A-01
00-15-5D-64-9A-02
00-15-5D-64-9A-03
00-15-5D-64-9A-05

How can I do this in the above one-liner?

Top 10 Contributor
Posts 640

You'd do this with select-object.

Get-VMNic | Select-Object -Property @{name='Address';expression={xxx}} | Sort-Object -Property Address

Whatever goes into 'xxx' would use '$_.Address' to access the original address property. Unfortunately, you're down to basic string manipulation, and PowerShell doesn't have a ton of great string manipulation capabilities. Just not its strong suit. So we'll probably have to use a method of the .NET System.String class. Assuming the existing address is a string...

$_.Address.Insert(2,'-').Insert(5,'-').Insert(8,'-').Insert(11,'-').Insert(14,'-')

Would go in place of 'xxx.' You may have to tweak the numeric values to get the insertion points right. See http://msdn.microsoft.com/en-us/library/system.string.insert.aspx for the Insert() method docs.

Top 75 Contributor
Posts 42
Microsoft MVP
Top Contributor

Here's another option using the -split operator:

 

PS> ('00155D649A01' -split '(..)' | Where-Object {$_}) -join '-'

00-15-5D-64-9A-01

 

And for all addresses:

Get-VMNic | Foreach-Object { ($_.Address -split '(..)' | Where-Object {$_}) -join '-' }

Page 1 of 1 (3 items) | RSS
Copyright 2012 PowerShell.com. All rights reserved.