Empty value powershell array

13,388

Solution 1

If you want exclude empty values you can do like this

$Serveur = $Serveur |  ? { $_ } | sort -uniq

Solution 2

In case someone (like me) needs to remove empty elements from array, but without sorting:

$Serveur = $Serveur | Where-Object { $_ } | Select -Unique

Solution 3

You have an array with 3 elements, so the count is 3. The element you got from the line ;;;;;;;; isn't $null, but an empty string (""), so it counts as a valid element. If you want to omit empty elements from the array, filter them out as C.B. suggested.

On a more general note, I'd recommend against using the += operator. Each operation copies the entire array to a new array, which is bound to perform poorly. It's also completely unnecessary here. Simply echo the value of the field and assign the output as a whole back to a variable:

$csv = 'C:\Users\aasif\Desktop\myfile.csv'
$Serveur = Import-Csv $csv -Delim ';' | % { $_.Serveur } | ? { $_ } | sort -uniq
Share:
13,388
Adeel ASIF
Author by

Adeel ASIF

DevOps engineer. Powershell expert. 29, Paris.

Updated on June 14, 2022

Comments

  • Adeel ASIF
    Adeel ASIF almost 2 years

    I have a strange issue, this is my CSV:

    Serveur;Carte;Cordon;IP;Mac;Vmnic ;Vmnic mac;Connect;Port
    Dexter;eth1;405;172.16.5.117;00:24:e8:36:36:df;Vmnic0;00:50:56:56:36:df;sw-front-1;A1
    Dexter;eth2;14;192.168.140.17;00:24:e8:36:36:e1;Vmnic1;00:50:56:56:36:e1; sw_eq_ds_1;3
    ;;;;;;;;
    Gordon;eth1;404;172.16.5.124;b8:ac:6f:8d:ac:b4;Vmnic0;00:50:56:5d:ac:b4;;
    Gordon;eth2;35;192.168.140.114;b8:ac:6f:8d:ac:b6;Vmnic1;00:50:56:5d:ac:b6;;
    Gordon;eth3;254;192.168.33.10;b8:ac:6f:8d:ac:b8;Vmnic2;00:50:56:5d:ac:b8;;
    

    So I imported it into an array with the following code:

    $Serveur = @()
    
    Import-Csv C:\Users\aasif\Desktop\myfile.csv -Delimiter ";" |`
        ForEach-Object {
            $Serveur += $_.Serveur
        }
    

    And to remove duplicate values I did this :

    $Serveur = $Serveur | sort -uniq
    

    So when I display my Array, I obtain these two values : Dexter and Gordon and a third null value

    But I also get an empty value

    The following code return 3

    $Serveur.count
    

    Why?

    Thanks for your help