2016-11-30 80 views
-1

好的 - 这是一个非常奇怪的问题 - 它可能有一个非常愚蠢的解决方案。无法在foreach循环中调用数组标题

但我导入CSV

$csv = import-csv c:\users\hello.csv 

然后,我有话阵列,对此我想使用通过CSV搜索 - 如果有一个在CSV比赛 - 填充相邻的列在csv。

这里的数组:

$newhandles 
hi 
hello 

现在 - 如果我运行foreach循环使用它内部的if语句 - 它不承认的标题之一。

foreach ($newhandle in $newhandles) 
{if ($csv.name -eq $newhandle) {$csv.redundant = $newhandle}} 

但是它给了我这个错误:

The property 'redundant' cannot be found on this object. Verify that the property exists 
and can be set. 
At line:1 char:69 
+ ... andles) {if ($csv.name -eq $newhandle) {$csv.redundant = $newhandle}} 
+            ~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
+ CategoryInfo   : InvalidOperation: (:) [], RuntimeException 
+ FullyQualifiedErrorId : PropertyAssignmentException 

我知道属性存在 - 因为如果我直接调用它 - 它显示了三个空的插槽 - 如果我直接调用的东西吧 - 元素将填充。如

> $csv[0].redundant = 'hi' 

> $csv[0] 


name  : hi 
description : don't settle 
system  : sight 
redundant : hi 
tags  : 

任何想法?

+0

手动检查你追加[0],但如果你在它的工作原理SIM卡层层引用整个$ csv.Name。当您手动输入$ csv.Name时会发生什么? – LotPings

回答

1

尝试使用此foreach循环:

foreach ($rec in $csv){ 
if($newhandles -contains $rec.name){ 
$rec.redundant = $rec.name 

} 

} 

如果你检查($ csv.redundant).GetType(),你可以看到它返回一个数组,而不是你想要的属性,但是当你正在分配价值$ CSV [0] .redundant您正在访问的确切性质,这就是为什么当你手动

+0

ahh - 因此您需要对实际的csv进行foreach以将其分解为每个ITS记录以便能够访问其每个属性。为什么$ newhandles会在-contains $ rec.name之前?不应该是如果($ rec.name -contains $ newhandles)? (现在不是那么重要,非常感谢。 –

0

测试试试这个

import-csv "c:\users\hello.csv" | select * , @{N="redundant";E={if ($newhandles -contains $_.Name) {$_.Name} else {$null}}} -ExcludeProperty redundant