Empty value powershell array

╄→尐↘猪︶ㄣ 提交于 2019-12-24 02:39:09

问题


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:


If you want exclude empty values you can do like this

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



回答2:


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



回答3:


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

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


来源:https://stackoverflow.com/questions/17704779/empty-value-powershell-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!