1

我想检查 .csv 数据库的“代码”属性的值。如果“代码”字段的前三个字符等于 (-eq) 到“产品”的前三个字符,则显示结果数(计数)并将输入添加到 .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 = @(Import-Csv $nonSortedCsv | where-Object { ($_.Code.split('-')[0]) -eq $firstKey })

显然,当 CSV 文件中只有一行时,Import-Csv 返回一个 PSCustomObject。当多于一行时,返回的对象是一个Object[]。

4

1 回答 1

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

于 2013-03-19T10:55:21.153 回答