rookie_b
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:
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!
$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()}
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!
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Never mind, can no longer replicate my original problem with $_.trim() not working. And this solution is much more elegant and efficient.
ASKER
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.