2012-06-20 41 views
1

我想檢查.csv數據庫的「Code」屬性的值。如果「代碼」字段的前三個字符等於(-eq)到「產品」的前三個字符,則顯示結果數(計數)並將輸入添加到.csv數據庫。Powershell Import-Csv結果數

但是,計數不會顯示爲結果爲空。

foreach ($row in $InventoryContents) 
{ 
    #Lets build a String first 
    $exportString = $row.User +','+$row.Product+','+$row.Company+','+$row.Model+','; 
    #Everything right so far 

    #first three characters of Product 
    $firstKey = $row.Product.SubString(0,3).ToUpper() 
    echo $firstKey; 

    #problem here 
    $nonSortedContents = Import-Csv $nonSortedCsv | where-Object { ($_.Code.split('-')[0]) -eq $firstKey } 
    #but arrapently this works : Import-Csv $nonSortedCsv| where-Object { ($_.Code.split('-')[0]) -eq "MON"} 


    $lines = $nonSortedContents.count 
    echo $lines 
    #null 


    #if not enetered 
    if ($lines -eq $null) 
    { 
      $wholeKey = $firstKey +'-'+ ("{0:D5}" -f 0).ToString() 
      $exportString = $exportString + $wholeKey 
      $exportString -join "," >> $nonSortedCsv 
    } 
    else 
    { 
      $wholeKey = $firstKey +'-'+ ("{0:D5}" -f $lines).ToString() 
      $exportString = $exportString + $wholeKey 
      $exportString -join "," >> $nonSortedCsv 
    } 
} 

我得到了它與

$ nonSortedContents = @(進口-CSV $ nonSortedCsv工作|。其中,對象{($ _ Code.split( ' - ')[0] )-eq $ firstKey})

顯然,當CSV文件中只有一行時,Import-Csv會返回一個 PSCustomObject。當有多行時,返回的對象是一個 Object []。

+0

感謝。遇到同樣的問題。 – grenade

回答

0

我有一個條件填充陣列類似的問題:

$csv = if ($someCondition) { 
    @(Import-CSV someFile.csv) 
} else { 
    @(Import-CSV someFile.csv | Where-Object { $_.someColumn -eq "someValue" }) 
} 

然而,僅僅圍繞與陣列符號@(...)Import-CSV線是不夠的。在我的情況下,我不得不顯式聲明變量爲一個數組([array] $csv)。例如:

[array] $csv = if ($someCondition) { 
    @(Import-CSV someFile.csv) 
} else { 
    @(Import-CSV someFile.csv | Where-Object { $_.someColumn -eq "someValue" }) 
} 

我提示從這裏:http://poshoholic.com/2009/07/03/powershell-quick-tip-when-you-store-an-array-make-sure-it-is-an-array/這裏:https://groups.google.com/forum/#!msg/microsoft.public.windows.powershell/L5J3WffAu9A/vK1mKj2nVncJ

+0

由於周圍的「if」,它「不夠」嗎?也就是說,我相信從'if'返回'像'Import-CSV'一樣展開單項數組。這意味着你可以在你的'if'子句中刪除周圍的@()';他們只是裝箱價值立即拆箱,因爲它返回。相反,*簡單地*像你一樣強制一個數組,或者可能包圍整個'if' - '$ a = @(if($ true){Import-Csv someFile.csv} ...) - 如果你相反,總是返回一個數組。 – ruffin