≡ 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.

Comments on this entry are closed.

  • 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

    • mrutgers April 30, 2018, 1:07 am

      Removes leading / trailing spaces of each item, and removes items consisting only of whitespace:
      $content = $content | %{$_.trim()} | ? {$_}

      • Wintel Rocks May 29, 2018, 6:10 pm

        That’s a good suggestion. I will update the post with that.

  • 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.

    • Wintel Rocks June 27, 2017, 2:19 pm

      You are correct Brent. I love the regex way.

      • Kerry Webster January 17, 2018, 12:48 am

        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

        • Kerry Webster January 17, 2018, 12:56 am

          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.

  • Tony September 6, 2017, 3:16 pm

    Thank,s for good explanation and example.
    /Tony

  • Randy October 14, 2017, 10:16 pm

    Tremendously helpful. (yes, even a couple years later)
    Thank you very much.

  • Anup tiwari August 26, 2019, 3:35 pm

    well the first one worked like a champ …thanks dude.:)

  • Anonyposh May 26, 2021, 4:45 am

    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(”)
    }