I’ve always struggled with text. Now I really hate text. I love objects. But sometimes you can’t avoid these non-object-oriented characters coming from somewhere else. This blog post is about text and its formatting. We will concentrate on the methods trim, replace and split. And we will use an example: arp -a.
Starting Point (arp -a)
Where do we start? As promised we are going to use the good old arp command. Let’s have a look at arp. It’s result is plain text.
Let’s say we would like to list only the IP Addresses without the other stuff. It should look like this:
How to get started? First, we are going to delete all whitespaces with the trim method.
Trim
Trim can help you removing all those annoying whitespaces at the beginning and at the end. Let’s do it.
$a=arp -a $b=$a.Trim()
Nice one. Comparing to the previous they are all gone.
Skip
Our next part is to remove the first three lines.
This takes us to skip. Let’s move on and remove the first 3 lines with Select-Object.
$c=$b | Select-Object -Skip 3
And finally they are gone.
Now we have a good basis.
Replacing all whitespaces with one whitespace
Let’s go on with removing all unnecessary whitespaces.
With this simple replace statement we replace all whitespaces (\s+) with one whitespace.
$d= $c -replace '\s+', ' '
Splitting
At this stage we arrive at split. All we need is one row with all the values.
$e=$d -split(' ') $e
But we just want the IP-Addresses. That’s why we need to get to every third line. Now we are coming to the last part that is the most demanding one: Getting every 3rd line.
Looping through every 3rd line
Our goal is clear. List only every 3rd line.
We start at zero. Then we define the end of the loop. Then we define every 3rd line.
$f=for ($i=0;$i -lt $e.count;$i+=3) {$e[$i]} $f
Great, we’ve reached our goal.
All together
To get to the point, all at once in a slightly different order.
$a=arp -a | Select -Skip 3 $b=$a.Trim() -replace '\s+',' ' -split '\s' $c=for ($i=0;$i -lt $b.count;$i+=3) {$b[$i]} $c
Another final example (quser)
How to get the logged in user from quser? I’m talking about this. Simple text again.
What I would like to mention first is that there are hundreds if not thousands of ways to get the username. Here is my approach which is quite similar to the shown above.
It is not as difficult as the one shown above. All we need is the username. No loop. Let’s trim first. The username is in 8th place.
$a=quser $b=$a.trim() -replace '\s+',' ' -replace '>','' -split ' ' $b[8]
That’s it for today. Don’t worry about dealing with text 😉
Categories: PowerShell
Why loop through $e to get every third line when you can just index the result from the -split operator non-skipped line result from arp?
Like this, I mean: $f = ($d -split ‘ ‘)[0]
So that would give you this one-liner:
arp -a | select -skip 3 | foreach { ($_.Trim() -replace ‘\s+’,’ ‘ -split ‘\s’)[0] }
LikeLiked by 1 person
Many ways to Rome …
Thank you for sharing a different approach.
LikeLike