Often we get this situation where in you read the contents of a file for servers list or some other content and end up with blank/empty items in the array because of empty lines in the files. This is often seen when doing split operation on array and because of string format you will end up with empty items in array.
The below example will give you understanding of what I am saying. Scenario#1 shows how blank entries will get added to array when you read the file contents using Get-Content cmdlets and Scenario#2 shows how you will end up with blank/empty entries when you split a string using Split() method. These are two most common cases where you will end up with empty items in resultant array.
Now let us go ahead and see how to get rid of them.
Addressing scenario#1:
It can be addressed by using simple technique where you will check each item in array and verify if it is empty or not. Need even shorter solution? Try the below.
$content = Get-Content c:\temp\servers.txt Write-Host "Array size before removing empty lines : $($content.Count)" $content = $content | ? {$_} Write-Host "Array size AFTER removing empty lines : $($content.Count)"
I am not aware of any other better approaches, please feel free to share if you have better technique.
Addressing scenario#2:
Scenario#2 can also be addressed in same way as scenario#1 but I don’t want to do it since there is better approach. Let me be a good programmer.
$string = "try;splitting;;me;;by semi;;coluns;;to see what ;; happens;ok?" $string.Split(";",[System.StringSplitOptions]::RemoveEmptyEntries)
As you can see split() method can take a optional parameter called splitoptions where we can specify it to remove empty entries.
As you can see in output, empty lines are removed now.
Comments on this entry are closed.
Very nice, Thanks!
For option #2, I would still run into issues because from time to time I need to remove empty lines and lines that are a single character. I also find it easier to understand, but maybe I’m a bad programmer.
Hello In scnearion 1# it didn;t removed any empty lines but i got the same error any suggestions.
# Path to the file containing FedEx server names.
$svrs = (get-content C:\Powershell\Servers.txt),
# Used for date comparisons.
$dat = (Get-date -format “yyyyMMdd”),
# Variable to verify that something was processed before
$count = 0,
$content = Get-Content \\conway\it\trax\Application\Hardware\FedEx_Servers.txt
Write-Host “Array size before removing empty lines : $($content.Count)”
$content = $content | ? {$_}
Write-Host “Array size AFTER removing empty lines : $($content.Count)”
# Used to avoid empty array errors messages.
[Array[]] $meters = @()
)
PS U:\> Check-FedExExpiry
% : Cannot index into a null array.
At C:\PowerShell\FedEx_Meter_Check.ps1:31 char:18
+ $d | % {
+ ~~~
+ CategoryInfo : InvalidOperation: (:) [ForEach-Object], RuntimeException
+ FullyQualifiedErrorId : NullArray,Microsoft.PowerShell.Commands.ForEachObjectCommand
Removes leading / trailing spaces of each item, and removes items consisting only of whitespace:
$content = $content | %{$_.trim()} | ? {$_}
That’s a good suggestion. I will update the post with that.
Hello,
In your scenario 2, how would you go about removing the blank infrom of the word “happens”
Regards,
Carter
I see this as a good opportunity to use the power of RegEx to solve this one…
Why not use something like this $string -split “\s*;+\s*”
Cheers
Brent.
You are correct Brent. I love the regex way.
Scenario #1
$serverList=”c:\temp\server-names.cfg”
$serverNames=(Get-Content $serverList) -notmatch ‘^\s*$’
You can pipe to sort if needed: $serverNames=(Get-Content $serverList) -notmatch ‘^\s*$’ | sort
Will get line feeds as well as white space.
Test contents of server-names.cfg:
server-name-001
server-name-002
server-name-007
server-name-003
server-name-005
server-name-006
server-name-004
server-name-008
server-name-009
server-name-000
I like your syntax better for getting just the blank line/whitspace line. Elegant.
You can use my syntax for excluding lines that begin with other characters like comments:
#line1
#line 2
line 3
line 4
If server-names contained the above text
$serverList=”c:\temp\server-names.cfg”
$serverNames=(Get-Content $serverList) -notmatch ‘^#’
#line 1 and #line 2 would be skipped. line 3 & line 4 included.
Just another approach using regex.
Thank,s for good explanation and example.
/Tony
Tremendously helpful. (yes, even a couple years later)
Thank you very much.
Glad that it is helpful.
well the first one worked like a champ …thanks dude.:)
This should work as well. Good day!
function Convert-StringToReverse() {
Param(
[Parameter(Mandatory=$True, Position=0)]
[string] $stringIn
)
$stringLength = $stringIn.Length
$reverseRange = $stringLength..0
return $stringIn[$reverseRange] -join(”)
}