Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

share|improve this question
1  
i get three values, one of them empty. when you say "when i display my Array, what are you actually doing? –  Jimbo Jul 17 '13 at 18:12

2 Answers 2

up vote 4 down vote accepted

If you want exclude empty values you can do like this

$Serveur = $Serveur |  ? { $_ } | sort -uniq
share|improve this answer

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|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.