我想检查.csv数据库的“Code”属性的值。如果“代码”字段的前三个字符等于(-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。当有多行时,返回的对象是 对象[]。
答案 0 :(得分: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