Avatar of rookie_b
rookie_b
Flag for United Kingdom of Great Britain and Northern Ireland asked on

How to trim current pipeline object in PowerShell?

I often paste input into ISE and sometimes it needs trimming empty lines and leading/trailing spaces, so I need to  pipe it to trim those:

$lines = $null

$lines = @"

 \\server\share\folder
  \\server\share\folder2  

\\server2\share\folder
    \\server2\share\folder2   

"@ -split "\t|\r?\n" |?{$_ -match "\w"} |ForEach-Object {($_ -replace "").trim()}

Open in new window


So, using $_ -match \w covers me when the lines contain letters and/or numbers, which works in my particular case, but I assume there is a proper way to exclude empty lines?

Also, ($_).trim() doesn't seem to work, so I am having to do something to $_like $_ -replace ""  (which I am hoping does nothing?), before trim actually works. So, what is the proper way to trim the object in the pipeline? I am guessing turn it into a string somehow?

Or is there a better way of doing all this altogether?

My goal is basically paste some input into ISE, split it into a multi line object, remove the empty lines, and trim the remaining lines.

Thank you!


PowershellWindows OS

Avatar of undefined
Last Comment
rookie_b

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
oBdA

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
rookie_b

ASKER
Well, that is very nice!

Just need to double-check and  try and figure out why {$_.Trim() } wouldn't work for me initially, so I had to use {($_ -replace "") .Trim() } just to have the .Trim() option available at all. It just wasn't working  for $_.trim().  Also,  the trimming wasn't getting rid of the empty lines, and in this example it does.

But it works for the example given. 
rookie_b

ASKER
Never mind, can no longer replicate my original problem with $_.trim() not working. And this solution is much more elegant and efficient.
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck