≡ Menu

Remove empty items from array in PowerShell

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.

array-emptylines

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)"

remove-emptylines-1

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)

remove-emptylines-2

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.

{ 7 comments… add one }
  • Tom Powell September 4, 2015, 1:14 am

    Very nice, Thanks!

  • Alex December 9, 2015, 3:08 am

    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.

  • Rahul August 12, 2016, 11:26 pm

    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

  • Carter January 13, 2017, 3:03 am

    Hello,

    In your scenario 2, how would you go about removing the blank infrom of the word “happens”

    Regards,

    Carter

  • brent April 21, 2017, 7:14 am

    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.

  • Tony September 6, 2017, 3:16 pm

    Thank,s for good explanation and example.
    /Tony

Leave a Comment