2

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

1
  • 1
    i get three values, one of them empty. when you say "when i display my Array, what are you actually doing? Commented Jul 17, 2013 at 18:12

3 Answers 3

9

If you want exclude empty values you can do like this

$Serveur = $Serveur |  ? { $_ } | sort -uniq
Sign up to request clarification or add additional context in comments.

Comments

7

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

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.