Techibee.com

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.

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.

Exit mobile version